forge
Explore
Log in

Don't you dare go Hollow

The codec stops replacing the whole program's allocator

Browse files at this commit

c8f62cbb65b8a92a4ae84482b7017d4e252642d1Ahmet Kaan GümüşParent: 64cb44f
  • fix
    • the codec stops replacing the whole program's allocator
Show full message
🐛 fix(engine): the codec stops replacing the whole program's allocator

`rusty_h264-common` declares `rusty_alloc` as the `#[global_allocator]` of
whatever links it, and its sibling decoder and encoder turn that feature on
from their own defaults -- so no downstream feature choice could decline it.
Sustained scrubbing churns decode-worker threads, and that allocator faulted
on both ends of a thread's life: on a new one's very first allocation, and
in `Heap::collect_inner` from the `thread_done` TSD destructor. Three cores.

`common` is vendored (the fifth, same idiom as the other four): the feature
stays declared so the sibling manifests still resolve, but it is empty and
the six-line declaration is gone. Not one line of codec code differs from
0.9.1 -- 360 decoded pictures across three fixtures still match ffmpeg's
`framemd5` exactly -- and the process gets glibc's malloc back.

21 changed files +11066 -39

Cargo.lockmodified+0 -31
@@ -5019,25 +5019,6 @@ checksum = "cf54715a573b99ac80df0bc206da022bcd442c974952c7b9720069370852e21f"
5019 name = "rusty_aac"5019 name = "rusty_aac"
5020 version = "0.5.0"5020 version = "0.5.0"
5021 5021
5022-[[package]]
5023-name = "rusty_alloc"
5024-version = "0.3.2"
5025-source = "registry+https://github.com/rust-lang/crates.io-index"
5026-checksum = "b5f05c71564028538eeba6e2e08c6a512267e85e6a1584beca45c6f26af8651b"
5027-dependencies = [
5028- "libc",
5029- "windows-sys 0.60.2",
5030-]
5031-
5032-[[package]]
5033-name = "rusty_alloc-api"
5034-version = "0.3.2"
5035-source = "registry+https://github.com/rust-lang/crates.io-index"
5036-checksum = "65c8c3ecd14424ba980d005147945a745836dea7798d447c419e08be1f79e88f"
5037-dependencies = [
5038- "rusty_alloc",
5039-]
5040-
5041 [[package]]5022 [[package]]
5042 name = "rusty_h264"5023 name = "rusty_h264"
5043 version = "0.9.1"5024 version = "0.9.1"
@@ -5052,11 +5033,8 @@ dependencies = [
5052 [[package]]5033 [[package]]
5053 name = "rusty_h264-common"5034 name = "rusty_h264-common"
5054 version = "0.9.1"5035 version = "0.9.1"
5055-source = "registry+https://github.com/rust-lang/crates.io-index"
5056-checksum = "ed3c3c7ad3a43386460736b7552ab82239bdd703bedcf8c7f5d0032c50cfb8cb"
5057 dependencies = [5036 dependencies = [
5058 "bytemuck",5037 "bytemuck",
5059- "rusty_alloc-api",
5060 "wide",5038 "wide",
5061 ]5039 ]
5062 5040
@@ -7217,15 +7195,6 @@ dependencies = [
7217 "windows-targets 0.52.6",7195 "windows-targets 0.52.6",
7218 ]7196 ]
7219 7197
7220-[[package]]
7221-name = "windows-sys"
7222-version = "0.60.2"
7223-source = "registry+https://github.com/rust-lang/crates.io-index"
7224-checksum = "f2f500e4d28234f72040990ec9d39e3a6b950f9f22d3dba18416c35882612bcb"
7225-dependencies = [
7226- "windows-targets 0.53.5",
7227-]
7228-
7229 [[package]]7198 [[package]]
7230 name = "windows-sys"7199 name = "windows-sys"
7231 version = "0.61.2"7200 version = "0.61.2"
Cargo.tomlmodified+16 -3
@@ -7,15 +7,16 @@ exclude = [
7 "vendor/cros-codecs",7 "vendor/cros-codecs",
8 "vendor/rusty_aac",8 "vendor/rusty_aac",
9 "vendor/oxideav-h265",9 "vendor/oxideav-h265",
10+ "vendor/rusty_h264-common",
10 ]11 ]
11 12
12 [workspace.package]13 [workspace.package]
13 version = "0.1.0"14 version = "0.1.0"
14 edition = "2024"15 edition = "2024"
15 16
16-# Four upstream crates vendored verbatim except for one clearly marked fix each,17+# Five upstream crates vendored verbatim except for one clearly marked fix each,
17 # all blockers on this machine and all still unfixed upstream as of18 # all blockers on this machine and all still unfixed upstream as of
18-# 0.0.6/0.0.13/0.5.0/0.0.9:19+# 0.0.6/0.0.13/0.5.0/0.0.9/0.9.1:
19 # cros-libva - fails to build against libva >= 1.23 headers20 # cros-libva - fails to build against libva >= 1.23 headers
20 # cros-codecs - probes VA-API with a 16x16 context that Mesa radeonsi refuses;21 # cros-codecs - probes VA-API with a 16x16 context that Mesa radeonsi refuses;
21 # and creates every decode context as 8-bit 4:2:0, which no HEVC22 # and creates every decode context as 8-bit 4:2:0, which no HEVC
@@ -38,8 +39,20 @@ edition = "2024"
38 # 69bde5a6e, and it is a plain path dependency (no39 # 69bde5a6e, and it is a plain path dependency (no
39 # `[patch.crates-io]` line) because nothing else in the tree40 # `[patch.crates-io]` line) because nothing else in the tree
40 # asks for it.41 # asks for it.
41-# Drop `vendor/` entirely once released versions handle all four.42+# rusty_h264-common - declares `rusty_alloc` (its authors' own mimalloc
43+# remake) as the `#[global_allocator]` of whatever application
44+# links it, under a feature that `rusty_h264-{decoder,encoder}`
45+# turn on from *their* defaults, so no downstream feature choice
46+# can decline it. It crashed us: under sustained ruler scrubbing
47+# edith churns decode-worker threads, and that allocator
48+# segfaulted inside `span_from_segments` on a new thread's first
49+# allocation (two cores, 2026-08-13). The patch is the feature
50+# default and the six-line declaration in `src/lib.rs`; every
51+# line of codec code is byte-identical to 0.9.1, so decode stays
52+# bit-exact and the process gets glibc's malloc back.
53+# Drop `vendor/` entirely once released versions handle all five.
42 [patch.crates-io]54 [patch.crates-io]
43 cros-libva = { path = "vendor/cros-libva" }55 cros-libva = { path = "vendor/cros-libva" }
44 cros-codecs = { path = "vendor/cros-codecs" }56 cros-codecs = { path = "vendor/cros-codecs" }
45 rusty_aac = { path = "vendor/rusty_aac" }57 rusty_aac = { path = "vendor/rusty_aac" }
58+rusty_h264-common = { path = "vendor/rusty_h264-common" }
crates/engine/Cargo.tomlmodified+7 -5
@@ -44,11 +44,13 @@ miniz_oxide = "0.8"
44 # What that line does not turn off, and cannot: the facade asks for its three44 # What that line does not turn off, and cannot: the facade asks for its three
45 # sub-crates with *their* defaults, and `rusty_h264-common`'s default installs45 # sub-crates with *their* defaults, and `rusty_h264-common`'s default installs
46 # `rusty_alloc` -- a pure-Rust mimalloc remake, MIT -- as the process-wide46 # `rusty_alloc` -- a pure-Rust mimalloc remake, MIT -- as the process-wide
47-# `#[global_allocator]`, for the whole application rather than the codec. No47+# `#[global_allocator]`, for the whole application rather than the codec. It was
48-# feature choice downstream switches it back off; only a vendored `common`48+# faster on a synthetic 2M-allocation churn (0.104 s against glibc's 0.142 s)
49-# would. It is not a regression to pay for: the same 2M-allocation churn runs in49+# and it crashed the editor: sustained scrubbing churns decode-worker threads,
50-# 0.104 s under it against 0.142 s under glibc's, so it stays, and this50+# and it segfaulted on a new thread's *first* allocation. `common` is therefore
51-# paragraph is the disclosure. Frame-threaded decode arrived in 0.9 as well and51+# vendored with that declaration removed (workspace root `[patch.crates-io]`),
52+# which is the only way to decline it -- the codec itself is untouched and still
53+# bit-exact. Frame-threaded decode arrived in 0.9 as well and
52 # is opt-in through `RS_H264_FRAME_THREADS`, unset here -- the decode loop is54 # is opt-in through `RS_H264_FRAME_THREADS`, unset here -- the decode loop is
53 # serial exactly as it was.55 # serial exactly as it was.
54 rusty_h264 = { version = "=0.9.1", default-features = false }56 rusty_h264 = { version = "=0.9.1", default-features = false }
vendor/rusty_h264-common/Cargo.tomladded+74 -0
@@ -0,0 +1,74 @@
1+# THIS FILE IS AUTOMATICALLY GENERATED BY CARGO
2+#
3+# When uploading crates to the registry Cargo will automatically
4+# "normalize" Cargo.toml files for maximal compatibility
5+# with all versions of Cargo and also rewrite `path` dependencies
6+# to registry (e.g., crates.io) dependencies.
7+#
8+# If you are reading this file be aware that the original Cargo.toml
9+# will likely look very different (and much more reasonable).
10+# See Cargo.toml.orig for the original contents.
11+
12+[package]
13+edition = "2021"
14+rust-version = "1.80"
15+name = "rusty_h264-common"
16+version = "0.9.1"
17+authors = ["Mata Network"]
18+build = "build.rs"
19+autolib = false
20+autobins = false
21+autoexamples = false
22+autotests = false
23+autobenches = false
24+description = "Shared primitives for the rusty_h264 pure-Rust H.264 codec: bitstream I/O, Exp-Golomb, NAL/Annex-B, transforms, intra prediction, motion compensation and deblocking. forbid(unsafe). BSD-2."
25+homepage = "https://www.mata.network/"
26+documentation = "https://docs.rs/rusty_h264-common"
27+readme = "README.md"
28+keywords = [
29+ "h264",
30+ "avc",
31+ "video",
32+ "codec",
33+ "bitstream",
34+]
35+categories = [
36+ "multimedia::video",
37+ "multimedia::encoding",
38+ "encoding",
39+]
40+license = "BSD-2-Clause"
41+repository = "https://github.com/remade-with-rust/rusty_h264"
42+
43+[features]
44+asm = ["dep:rusty_h264-accel"]
45+# --- edith patch: `global-alloc` is off by default and inert when asked for ---
46+# It stays *declared* because `rusty_h264-{decoder,encoder}`'s own defaults name
47+# `rusty_h264-common/global-alloc`, so removing it would break their manifests;
48+# it just no longer pulls `rusty_alloc-api` in, and lib.rs no longer installs the
49+# `#[global_allocator]`. See the note in the workspace root Cargo.toml.
50+default = []
51+global-alloc = []
52+profile = []
53+
54+[lib]
55+name = "rusty_h264_common"
56+path = "src/lib.rs"
57+
58+[[example]]
59+name = "bs_layout_ceiling"
60+path = "examples/bs_layout_ceiling.rs"
61+
62+[[example]]
63+name = "deblock_anatomy"
64+path = "examples/deblock_anatomy.rs"
65+
66+[dependencies.bytemuck]
67+version = "1"
68+
69+[dependencies.rusty_h264-accel]
70+version = "0.9.1"
71+optional = true
72+
73+[dependencies.wide]
74+version = "0.7"
vendor/rusty_h264-common/README.mdadded+122 -0
@@ -0,0 +1,122 @@
1+# rusty_h264-common
2+
3+[![crates.io](https://img.shields.io/crates/v/rusty_h264-common?logo=rust)](https://crates.io/crates/rusty_h264-common)
4+[![docs.rs](https://img.shields.io/docsrs/rusty_h264-common?logo=docsdotrs)](https://docs.rs/rusty_h264-common)
5+[![CI](https://github.com/remade-with-rust/rusty_h264/actions/workflows/ci.yml/badge.svg)](https://github.com/remade-with-rust/rusty_h264/actions/workflows/ci.yml)
6+[![License: BSD-2-Clause](https://img.shields.io/badge/license-BSD--2--Clause-blue)](https://github.com/remade-with-rust/rusty_h264/blob/main/LICENSE)
7+[![Remade With Rust](https://img.shields.io/badge/Remade%20With-Rust-000?logo=rust&logoColor=fff)](https://github.com/Remade-With-Rust)
8+[![By Mata Network](https://img.shields.io/badge/by-Mata%20Network-5b2be0)](https://www.mata.network/)
9+
10+> **The foundation both halves of the codec sit on.** Bitstream I/O, Exp-Golomb,
11+> NAL/Annex-B framing, the integer transforms, intra prediction, motion
12+> compensation and the deblocking filter — the shared `codec/common` layer of
13+> the pure-Rust [`rusty_h264`](https://crates.io/crates/rusty_h264) codec.
14+
15+**Most users want the facade — [`rusty_h264`](https://crates.io/crates/rusty_h264).**
16+Depend on this crate directly only if you are building on the primitives (a
17+custom parser, an analyzer, your own codec) rather than encoding or decoding.
18+
19+Part of **[Remade With Rust](https://github.com/Remade-With-Rust)** by
20+**[Mata Network](https://www.mata.network/)**.
21+
22+---
23+
24+## Why it's `forbid(unsafe_code)`
25+
26+The bit-twiddling core of an H.264 codec — Exp-Golomb reads off a hostile
27+bitstream, RBSP emulation handling, block-level pixel loops — is *exactly* where
28+memory-safety bugs hide in the C implementations. So this crate is
29+`#![forbid(unsafe_code)]`, and the shared reconstruction path here is what makes
30+the encoder and decoder agree bit-for-bit.
31+
32+The single exception is opt-in and never shipped: the `profile` feature relaxes
33+the attribute to unlock the `rdtsc` timer in [`prof`](https://docs.rs/rusty_h264-common/latest/rusty_h264_common/prof/)
34+for stage measurement. The release build forbids `unsafe`.
35+
36+## Modules
37+
38+| Module | What's in it |
39+|---|---|
40+| `bit_writer` / `bit_reader` | MSB-first bit packing and parsing, Exp-Golomb (`ue`/`se`), bounded reads that return `OutOfData` instead of panicking |
41+| `nal` | NAL units, Annex-B framing (`split_annex_b`), RBSP emulation prevention/unprevention |
42+| `types` | `YuvFrame` (raw planar I420), `Profile`, `ChromaFormat` |
43+| `transform` | 4×4 and 8×8 integer transforms, quantization/dequantization, luma & chroma DC Hadamard, scaling matrices |
44+| `predict` | Intra prediction — `I_16x16`, `I_4x4`, `I_8x8`, chroma 8×8 |
45+| `inter` | Quarter-pel luma motion compensation (6-tap), chroma MC, the interpolation half-pel planes |
46+| `deblock` | The in-loop deblocking filter, luma + chroma, 8×8-transform-aware |
47+| `cavlc` | CAVLC residual coding tables — table-driven **O(1)** decode (was O(bits·candidates)) |
48+| `cabac_tables` | The 460-context CABAC initialization tables shared by both entropy engines |
49+| `aligned` | `AlignedBytes` — a safe `[u8]` ↔ `[u128]` view (via `bytemuck`) giving 16-byte-aligned plane rows so the SIMD kernels can use aligned loads without `unsafe` here |
50+| `prof` | Dev-only `rdtsc` stage profiler, behind the `profile` feature — zero cost when off |
51+
52+Also exported: `ACCEL: bool`, whether the vendored SIMD kernels are actually
53+compiled in. Benchmarks read it so a harness that silently fell back to the
54+scalar twin can't report the fast path's number.
55+
56+## Features
57+
58+| Feature | Default | Effect |
59+|---|:--:|---|
60+| `asm` | — | Route the hot kernels (deblock, MC, transforms, intra pred) through the vendored openh264 SIMD asm in [`rusty_h264-accel`](https://crates.io/crates/rusty_h264-accel). The `unsafe` FFI stays quarantined there; this crate calls only its safe wrappers and remains `forbid(unsafe)`. x86-64 + `nasm`. |
61+| `profile` | — | Enable the in-process stage profiler. Measurement builds only — never ship it. |
62+
63+SIMD is enabled through the facade's default `asm` feature; when this crate is
64+used standalone the scalar path is the default.
65+
66+## Install
67+
68+```sh
69+cargo add rusty_h264-common
70+```
71+
72+```rust
73+use rusty_h264_common::BitReader;
74+use rusty_h264_common::nal::{emulation_unprevent, split_annex_b};
75+
76+// Walk an Annex-B stream and read each NAL's header + first Exp-Golomb field.
77+for nal in split_annex_b(&stream) {
78+ let rbsp = emulation_unprevent(nal);
79+ let mut r = BitReader::new(&rbsp);
80+ let _forbidden_zero = r.read_bits(1)?;
81+ let _nal_ref_idc = r.read_bits(2)?;
82+ let nal_unit_type = r.read_bits(5)?;
83+ println!("nal type {nal_unit_type}, first ue = {}", r.read_ue()?);
84+}
85+```
86+
87+## Where this sits
88+
89+| Crate | Role |
90+|---|---|
91+| [`rusty_h264`](https://crates.io/crates/rusty_h264) | the public, safe facade API — **depend on this** |
92+| **[`rusty_h264-common`](https://crates.io/crates/rusty_h264-common)** | **← you are here** — bitstream I/O, transforms, prediction, MC, deblock |
93+| [`rusty_h264-encoder`](https://crates.io/crates/rusty_h264-encoder) | the encode pipeline |
94+| [`rusty_h264-decoder`](https://crates.io/crates/rusty_h264-decoder) | the decode pipeline |
95+| [`rusty_h264-accel`](https://crates.io/crates/rusty_h264-accel) | optional openh264 SIMD asm — the one `unsafe` crate |
96+
97+The workspace mirrors Cisco openh264's `codec/` tree; this crate is
98+`codec/common`.
99+
100+## The Remade With Rust ecosystem
101+
102+<!-- ORG BOILERPLATE — keep identical across repos -->
103+
104+**Remade With Rust** is an initiative by **[Mata Network](https://www.mata.network/)**
105+to rebuild essential C and C++ tools in Rust — for the memory safety, the
106+predictable performance, and the freedom of a permissive license. Each project
107+is a reimplementation, not a fork: same wire protocols and file formats, new
108+code you can actually depend on. No copyleft. No surprises.
109+
110+| Project | What it is |
111+|---|---|
112+| 🎬 **[remade_ffmpeg_rs](https://github.com/Remade-With-Rust/remade_ffmpeg_rs)** | **Our FFmpeg alternative.** Drop-in `ffmpeg` and `ffprobe` binaries — demux → decode → filter → encode → mux, rebuilt as composable Rust crates with **zero GPL/LGPL**. Apache-2.0. `rusty_h264` is its H.264 codec. |
113+| 🧠 **[FFAI](https://github.com/Remade-With-Rust/FFAI)** | **Our sister project: media *for* AI.** "The AI media toolkit, remade with rust." Embedded ASR + TTS (**Mercury**), OCR (**Carmenta**) and vision-language captioning (**Argus**) behind an ffmpeg-style, swap-by-name architecture — no Python, no CUDA. MIT OR Apache-2.0. |
114+| 🌐 **[Mata Network](https://www.mata.network/)** | **The home page.** *"Stop sacrificing your privacy for convenience."* Sovereign, self-hostable privacy infrastructure — wallet & identity, password manager, contact manager, and a browser extension that stops information leaking as you browse. Remade With Rust is its open-source arm. |
115+
116+→ All projects: **[github.com/Remade-With-Rust](https://github.com/Remade-With-Rust)**
117+
118+<!-- /ORG BOILERPLATE -->
119+
120+## License
121+
122+BSD-2-Clause — see [LICENSE](https://github.com/remade-with-rust/rusty_h264/blob/main/LICENSE).
vendor/rusty_h264-common/build.rsadded+18 -0
@@ -0,0 +1,18 @@
1+//! Defines the internal `accel` cfg = "the `asm` feature is on AND we target x86_64".
2+//!
3+//! The vendored openh264 SIMD kernels in `rusty_h264-accel` are x86-64 only, so the
4+//! `accel` code paths must not be compiled on other architectures even when a downstream
5+//! crate enables the (default) `asm` feature. On non-x86_64 targets `accel` stays unset
6+//! and the codec uses its pure-Rust scalar path — so e.g. `rff` builds on arm64 macOS
7+//! with default features and without nasm.
8+fn main() {
9+ // Declare the custom cfg so `unexpected_cfgs` (Rust 1.80+) stays quiet; older Cargo
10+ // ignores the line (and lacks the lint anyway).
11+ println!("cargo::rustc-check-cfg=cfg(accel)");
12+ let asm = std::env::var_os("CARGO_FEATURE_ASM").is_some();
13+ let x86_64 = std::env::var("CARGO_CFG_TARGET_ARCH").as_deref() == Ok("x86_64");
14+ if asm && x86_64 {
15+ // Single-colon form: understood by every Cargo version.
16+ println!("cargo:rustc-cfg=accel");
17+ }
18+}
vendor/rusty_h264-common/examples/bs_layout_ceiling.rsadded+251 -0
@@ -0,0 +1,251 @@
1+//! CEILING PROBE — is the bS derivation's 25x gap vs x264 really about LAYOUT?
2+//!
3+//! `docs/WHYS-decoder-perf.md` established: bS derivation is ~20% of decode at
4+//! ~400 ns/MB, against x264's `deblock_strength_avx2` at ~15 ns/MB, and the Step 0
5+//! audit showed our derivation emits ZERO packed ops because `gather_tile` is a
6+//! gather — 24 blocks across 4-6 SEPARATE frame-wide arrays.
7+//!
8+//! The hypothesis is that x264 wins on LAYOUT (packed per-MB nnz bitmask + per-MB
9+//! contiguous ref/mv) and that the SIMD is downstream of it. That implies a large,
10+//! risky refactor of the decoder's macroblock loop, so PROVE THE CEILING FIRST:
11+//! measure the gather alone, current layout vs packed, with no decoder changes.
12+//!
13+//! The probe deliberately measures ONLY the gather. If packed-vs-strided is a small
14+//! ratio here, the refactor cannot pay however good a kernel sits behind it — and
15+//! that is a whole day saved for twenty minutes of probe.
16+//!
17+//! Also reports a DETERMINISTIC cache-line count, because this box cannot currently
18+//! resolve timing (see the noise-floor sections of the WHYS doc): the line count is
19+//! the part of the answer that machine load cannot touch.
20+//!
21+//! ```text
22+//! cargo run --release -p rusty_h264-common --example bs_layout_ceiling
23+//! ```
24+
25+use std::hint::black_box;
26+use std::time::Instant;
27+
28+const MB_W: usize = 80; // 1280/16
29+const MB_H: usize = 45; // 720/16
30+const W4: usize = MB_W * 4;
31+
32+/// The CURRENT shape: separate frame-wide arrays, one per field.
33+struct Soa {
34+ inter: Vec<bool>,
35+ nnz: Vec<u8>,
36+ mv: Vec<(i32, i32)>,
37+ ref_id: Vec<i32>,
38+}
39+
40+/// The PACKED shape, mirroring x264's per-macroblock cache: everything one
41+/// macroblock's derivation needs, contiguous, in raster order.
42+///
43+/// `nnz` collapses to a 16-BIT MASK — the derivation only ever asks "is this block
44+/// coded", never for the count — which is also what makes the coefficient half of
45+/// the strength test a shift-and-or on a single register instead of 32 byte loads.
46+#[derive(Clone, Copy, Default)]
47+#[repr(C, align(64))]
48+struct MbRec {
49+ nnz_mask: u16,
50+ inter: bool,
51+ _pad: u8,
52+ ref_id: [i16; 16],
53+ mv: [(i16, i16); 16],
54+}
55+
56+fn build_soa() -> Soa {
57+ let n = W4 * MB_H * 4;
58+ // Deterministic pseudo-random content; a plausible mix of coded/uncoded and
59+ // varying motion, so neither layout gets an unrealistically friendly pattern.
60+ let mut s = 0x2545F491u32;
61+ let mut rnd = move || {
62+ s ^= s << 13;
63+ s ^= s >> 17;
64+ s ^= s << 5;
65+ s
66+ };
67+ let mut soa =
68+ Soa { inter: vec![true; n], nnz: vec![0; n], mv: vec![(0, 0); n], ref_id: vec![0; n] };
69+ for i in 0..n {
70+ let r = rnd();
71+ soa.inter[i] = (r & 0x1f) != 0; // ~3% intra
72+ soa.nnz[i] = if (r >> 5) & 3 == 0 { 1 } else { 0 };
73+ soa.mv[i] = (((r >> 7) & 0x3f) as i32 - 32, ((r >> 13) & 0x3f) as i32 - 32);
74+ soa.ref_id[i] = ((r >> 19) & 1) as i32;
75+ }
76+ soa
77+}
78+
79+fn build_packed(soa: &Soa) -> Vec<MbRec> {
80+ let mut v = vec![MbRec::default(); MB_W * MB_H];
81+ for mb_y in 0..MB_H {
82+ for mb_x in 0..MB_W {
83+ let rec = &mut v[mb_y * MB_W + mb_x];
84+ let (bx0, by0) = (mb_x * 4, mb_y * 4);
85+ rec.inter = soa.inter[by0 * W4 + bx0];
86+ for r in 0..4 {
87+ for c in 0..4 {
88+ let i = (by0 + r) * W4 + bx0 + c;
89+ let k = r * 4 + c;
90+ if soa.nnz[i] != 0 {
91+ rec.nnz_mask |= 1 << k;
92+ }
93+ rec.ref_id[k] = soa.ref_id[i] as i16;
94+ rec.mv[k] = (soa.mv[i].0 as i16, soa.mv[i].1 as i16);
95+ }
96+ }
97+ }
98+ }
99+ v
100+}
101+
102+/// ARM A — the gather as it exists today: 24 blocks, each pulling from 4 separate
103+/// frame-wide arrays at a strided index.
104+#[inline(never)]
105+fn gather_strided(soa: &Soa, mb_x: usize, mb_y: usize) -> u64 {
106+ let (bx0, by0) = (mb_x * 4, mb_y * 4);
107+ let mut acc = 0u64;
108+ let mut take = |i: usize| {
109+ acc = acc
110+ .wrapping_add(soa.inter[i] as u64)
111+ .wrapping_add(soa.nnz[i] as u64)
112+ .wrapping_add(soa.ref_id[i] as u64)
113+ .wrapping_add(soa.mv[i].0 as u64)
114+ .wrapping_add(soa.mv[i].1 as u64);
115+ };
116+ for r in 0..4 {
117+ for c in 0..4 {
118+ take((by0 + r) * W4 + bx0 + c);
119+ }
120+ }
121+ if mb_x > 0 {
122+ for r in 0..4 {
123+ take((by0 + r) * W4 + bx0 - 1);
124+ }
125+ }
126+ if mb_y > 0 {
127+ for c in 0..4 {
128+ take((by0 - 1) * W4 + bx0 + c);
129+ }
130+ }
131+ acc
132+}
133+
134+/// ARM B — the same information out of packed per-macroblock records: one
135+/// contiguous record for this macroblock plus the left and top neighbours'.
136+#[inline(never)]
137+fn gather_packed(recs: &[MbRec], mb_x: usize, mb_y: usize) -> u64 {
138+ let cur = &recs[mb_y * MB_W + mb_x];
139+ let mut acc = cur.nnz_mask as u64 + cur.inter as u64;
140+ for k in 0..16 {
141+ acc = acc
142+ .wrapping_add(cur.ref_id[k] as u64)
143+ .wrapping_add(cur.mv[k].0 as u64)
144+ .wrapping_add(cur.mv[k].1 as u64);
145+ }
146+ if mb_x > 0 {
147+ let l = &recs[mb_y * MB_W + mb_x - 1];
148+ for r in 0..4 {
149+ let k = r * 4 + 3; // right-hand column of the left neighbour
150+ acc = acc
151+ .wrapping_add(l.ref_id[k] as u64)
152+ .wrapping_add(l.mv[k].0 as u64)
153+ .wrapping_add(l.mv[k].1 as u64);
154+ }
155+ }
156+ if mb_y > 0 {
157+ let t = &recs[(mb_y - 1) * MB_W + mb_x];
158+ for c in 0..4 {
159+ let k = 12 + c; // bottom row of the top neighbour
160+ acc = acc
161+ .wrapping_add(t.ref_id[k] as u64)
162+ .wrapping_add(t.mv[k].0 as u64)
163+ .wrapping_add(t.mv[k].1 as u64);
164+ }
165+ }
166+ acc
167+}
168+
169+fn main() {
170+ let soa = build_soa();
171+ let recs = build_packed(&soa);
172+ let mbs = MB_W * MB_H;
173+
174+ // ---- DETERMINISTIC part: distinct 64-byte cache lines touched per macroblock.
175+ // Immune to machine load, which is why it leads.
176+ let line = |addr: usize| addr / 64;
177+ let mut a_lines = std::collections::HashSet::new();
178+ let mut b_lines = std::collections::HashSet::new();
179+ let (mb_x, mb_y) = (MB_W / 2, MB_H / 2);
180+ let (bx0, by0) = (mb_x * 4, mb_y * 4);
181+ let base = |p: *const u8| p as usize;
182+ for r in 0..4 {
183+ for c in 0..4 {
184+ let i = (by0 + r) * W4 + bx0 + c;
185+ a_lines.insert(line(base(soa.inter.as_ptr() as *const u8) + i));
186+ a_lines.insert(line(base(soa.nnz.as_ptr()) + i));
187+ a_lines.insert(line(base(soa.ref_id.as_ptr() as *const u8) + i * 4));
188+ a_lines.insert(line(base(soa.mv.as_ptr() as *const u8) + i * 8));
189+ }
190+ }
191+ let rec_base = base(recs.as_ptr() as *const u8) + (mb_y * MB_W + mb_x) * size_of::<MbRec>();
192+ for off in (0..size_of::<MbRec>()).step_by(64) {
193+ b_lines.insert(line(rec_base + off));
194+ }
195+
196+ println!("bS-derivation LAYOUT ceiling probe — 720p, {mbs} macroblocks\n");
197+ println!("DETERMINISTIC (machine load cannot move these):");
198+ println!(" MbRec size {:>6} bytes", size_of::<MbRec>());
199+ println!(" cache lines / MB, strided SoA {:>6} (own 16 blocks x 4 arrays)", a_lines.len());
200+ println!(" cache lines / MB, packed {:>6}", b_lines.len());
201+ println!(
202+ " ratio {:>6.2}x fewer lines\n",
203+ a_lines.len() as f64 / b_lines.len().max(1) as f64
204+ );
205+
206+ // ---- TIMED part: best-of-N, arms ABBA-alternated. Caveated on purpose.
207+ let reps = 30;
208+ let (mut best_a, mut best_b) = (f64::MAX, f64::MAX);
209+ for rep in 0..reps {
210+ let run_a = || {
211+ let t = Instant::now();
212+ let mut acc = 0u64;
213+ for y in 0..MB_H {
214+ for x in 0..MB_W {
215+ acc = acc.wrapping_add(gather_strided(black_box(&soa), x, y));
216+ }
217+ }
218+ (t.elapsed().as_secs_f64(), black_box(acc))
219+ };
220+ let run_b = || {
221+ let t = Instant::now();
222+ let mut acc = 0u64;
223+ for y in 0..MB_H {
224+ for x in 0..MB_W {
225+ acc = acc.wrapping_add(gather_packed(black_box(&recs), x, y));
226+ }
227+ }
228+ (t.elapsed().as_secs_f64(), black_box(acc))
229+ };
230+ // Alternate which arm runs first so warm-up bias cancels.
231+ let (ta, tb) = if rep % 2 == 0 {
232+ let (ta, _) = run_a();
233+ let (tb, _) = run_b();
234+ (ta, tb)
235+ } else {
236+ let (tb, _) = run_b();
237+ let (ta, _) = run_a();
238+ (ta, tb)
239+ };
240+ best_a = best_a.min(ta);
241+ best_b = best_b.min(tb);
242+ }
243+ let ns = |t: f64| t * 1e9 / mbs as f64;
244+ println!("TIMED (best-of-{reps}, arms alternated — treat as INDICATIVE only;");
245+ println!(" this box has shown 45% within-arm spread under foreign load):");
246+ println!(" strided SoA gather {:>7.1} ns/MB", ns(best_a));
247+ println!(" packed gather {:>7.1} ns/MB", ns(best_b));
248+ println!(" ratio {:>7.2}x", best_a / best_b);
249+ println!("\nFor scale: the whole derivation measures ~400 ns/MB in context;");
250+ println!("x264's deblock_strength_avx2 does the entire job in ~15 ns/MB.");
251+}
vendor/rusty_h264-common/examples/deblock_anatomy.rsadded+177 -0
@@ -0,0 +1,177 @@
1+//! Deblock anatomy bench — isolates where `filter_frame` spends its time.
2+//!
3+//! Motivated by the video-tests function-level comparison, which put our
4+//! deblocking well behind x264's. x264 splits the work in two: boundary
5+//! strengths are derived in its MB-encode loop by an asm kernel
6+//! (`deblock_strength_avx2`, ~15 ns/MB measured in-context), and
7+//! `frame_deblock_row` only filters. Ours does both inside `filter_frame`, so a
8+//! stage-vs-stage read overstates the gap — and hides which half is actually slow.
9+//!
10+//! Four scenarios separate the two halves. The key one is `inter-bs0`: every
11+//! boundary strength derives to 0, so NO filter kernel runs and the number is
12+//! pure bS-derivation + loop glue.
13+//!
14+//! ```text
15+//! cargo run --release -p rusty_h264-common --features asm --example deblock_anatomy
16+//! ```
17+
18+use rusty_h264_common::deblock::{filter_frame, BlockInfo};
19+
20+struct Grid {
21+ inter: Vec<bool>,
22+ nnz: Vec<u8>,
23+ mv: Vec<(i32, i32)>,
24+ ref_id: Vec<i32>,
25+ t8x8: Vec<bool>,
26+}
27+
28+const NO_REF: i32 = i32::MIN;
29+
30+/// Build the per-4×4-block state for one scenario.
31+fn grid(kind: &str, mb_w: usize, mb_h: usize) -> Grid {
32+ let (w4, h4) = (mb_w * 4, mb_h * 4);
33+ let n = w4 * h4;
34+ let mut g = Grid {
35+ inter: vec![true; n],
36+ nnz: vec![0u8; n],
37+ mv: vec![(0i32, 0i32); n],
38+ ref_id: vec![0i32; n],
39+ t8x8: Vec::new(),
40+ };
41+ match kind {
42+ // Every block intra: bS is 4 on MB edges, 3 internally — maximum
43+ // filtering, and the bS derivation never reaches the motion comparison.
44+ "all-intra" => {
45+ g.inter.iter_mut().for_each(|b| *b = false);
46+ g.ref_id.iter_mut().for_each(|r| *r = NO_REF);
47+ }
48+ // Every MB a skip: all inter, no coefficients, one shared (ref, mv).
49+ // The flat-inter gate fires, so only MB edges are considered.
50+ "skip" => {}
51+ // Every block has coefficients: bS = 2 everywhere, so every edge filters.
52+ "inter-coded" => {
53+ g.nnz.iter_mut().for_each(|c| *c = 4);
54+ }
55+ // The isolator: all inter, no coefficients, motion that VARIES (so the
56+ // flat-inter gate cannot fire) but by less than one full sample (so every
57+ // bS still derives to 0 and no filter kernel runs). What remains is the
58+ // bS derivation and the loop around it, and nothing else.
59+ "inter-bs0" => {
60+ for (i, m) in g.mv.iter_mut().enumerate() {
61+ // ±1 quarter-pel: |Δ| < 4 for every neighbour pair ⇒ bS 0.
62+ *m = ((i % 2) as i32, ((i / 2) % 2) as i32);
63+ }
64+ }
65+ // Real content, unlike every scenario above, mixes intra/inter, coded and
66+ // uncoded blocks, and varying motion WITHIN a macroblock — so the bS
67+ // derivation's branches are unpredictable. The uniform scenarios let the
68+ // predictor get every branch right, which is why they came in at ~240
69+ // ns/MB while real clips measure ~650.
70+ "mixed" => {
71+ let mut st = 0x12345678u32;
72+ let mut rnd = || {
73+ st ^= st << 13;
74+ st ^= st >> 17;
75+ st ^= st << 5;
76+ st
77+ };
78+ for i in 0..n {
79+ let r = rnd();
80+ g.inter[i] = r & 7 != 0; // ~1 in 8 blocks intra
81+ g.nnz[i] = if r & 0x30 != 0 { (r >> 8 & 7) as u8 } else { 0 };
82+ g.mv[i] = (((r >> 11) & 15) as i32 - 8, ((r >> 15) & 15) as i32 - 8);
83+ g.ref_id[i] = if g.inter[i] { ((r >> 19) & 1) as i32 } else { NO_REF };
84+ }
85+ }
86+ _ => panic!("unknown scenario {kind}"),
87+ }
88+ g
89+}
90+
91+fn main() {
92+ let cases = [(176usize, 144usize, "QCIF"), (352, 288, "CIF"), (1280, 720, "720p")];
93+ let scenarios = ["all-intra", "inter-coded", "inter-bs0", "skip", "mixed"];
94+
95+ println!("ns per macroblock, best-of-30 per arm, arms alternated pass by pass
96+");
97+ println!(
98+ "{:<8} {:<12} {:>12} {:>12} {:>10}",
99+ "size", "scenario", "branchy", "branchless", "speedup"
100+ );
101+ println!("{}", "-".repeat(60));
102+
103+ for (w, h, label) in cases {
104+ let (mb_w, mb_h) = (w / 16, h / 16);
105+ let mbs = mb_w * mb_h;
106+ let (cw, ch) = (w / 2, h / 2);
107+ let mb_qp = vec![26u8; mbs];
108+
109+ for kind in scenarios {
110+ let g = grid(kind, mb_w, mb_h);
111+ // Content shaped like a real RECONSTRUCTION, not noise. The filter
112+ // rejects an edge whose |p0-q0| >= alpha or |p1-p0| >= beta (~13/~6 at
113+ // QP 26), so high-frequency synthetic data makes it early-out and the
114+ // bench silently measures a filter that is barely running. A slow ramp
115+ // with a small step at each 4-sample block boundary — exactly the
116+ // blocking artefact deblocking exists to remove — keeps every edge
117+ // inside the thresholds, so the kernels do their full work.
118+ let px = |x: usize, yy: usize| -> u8 {
119+ let ramp = 100 + ((x / 8 + yy / 8) % 24);
120+ let step = ((x / 4) % 3) + ((yy / 4) % 2); // small block-edge discontinuity
121+ (ramp + step) as u8
122+ };
123+ let y0: Vec<u8> = (0..w * h).map(|i| px(i % w, i / w)).collect();
124+ let u0: Vec<u8> = (0..cw * ch).map(|i| px(i % cw, i / cw)).collect();
125+ let v0: Vec<u8> = (0..cw * ch).map(|i| px((i % cw) + 3, i / cw)).collect();
126+ let (mut y, mut u, mut v) = (y0.clone(), u0.clone(), v0.clone());
127+
128+ // ALTERNATE the two bS arms pass by pass so both see the same
129+ // thermal state; separate builds drift ~20% on this machine, which is
130+ // larger than the effect being measured.
131+ let mut best = [f64::MAX; 2];
132+ for pass in 0..60 {
133+ let branchless = pass % 2 == 0;
134+ rusty_h264_common::deblock::set_branchless_bs(branchless);
135+ // CRITICAL: filter_frame smooths in place. Without restoring the
136+ // source each pass, successive iterations run on progressively
137+ // flatter data, the filter's α/β early-outs start firing, and
138+ // best-of-N reports the cheapest (most-smoothed) pass rather than
139+ // the real cost. Restore outside the timed region.
140+ y.copy_from_slice(&y0);
141+ u.copy_from_slice(&u0);
142+ v.copy_from_slice(&v0);
143+ let info = BlockInfo {
144+ inter: &g.inter,
145+ nnz: &g.nnz,
146+ mv: &g.mv,
147+ ref_id: &g.ref_id,
148+ mv1: &[],
149+ ref_id1: &[],
150+ w4: mb_w * 4,
151+ t8x8: &g.t8x8,
152+ poc0: &[],
153+ poc1: &[],
154+ bs: &[], kind: &[],
155+ };
156+ let t = std::time::Instant::now();
157+ filter_frame(&mut y, &mut u, &mut v, mb_w, mb_h, &mb_qp, 0, 0, 0, &info);
158+ let e = t.elapsed().as_secs_f64();
159+ let slot = if branchless { 0 } else { 1 };
160+ if e < best[slot] {
161+ best[slot] = e;
162+ }
163+ std::hint::black_box((&y, &u, &v));
164+ }
165+ let ns = |t: f64| t * 1e9 / mbs as f64;
166+ println!(
167+ "{:<8} {:<12} {:>12.1} {:>12.1} {:>9.2}x",
168+ label,
169+ kind,
170+ ns(best[1]),
171+ ns(best[0]),
172+ ns(best[1]) / ns(best[0])
173+ );
174+ }
175+ println!();
176+ }
177+}
vendor/rusty_h264-common/src/aligned.rsadded+55 -0
@@ -0,0 +1,55 @@
1+//! A 16-byte-aligned heap byte buffer for the openh264 spatial asm kernels.
2+//!
3+//! openh264's deblock / MC / intra-prediction asm load aligned 16-byte row chunks
4+//! (`movdqa`), which a plain `Vec<u8>` (alignment 1) cannot satisfy. [`AlignedBytes`]
5+//! is backed by a `Vec<u128>` (alignment 16) and viewed as `[u8]` through `bytemuck`
6+//! — guaranteed 16-aligned, no `unsafe`. It `Deref`s to `[u8]`, so it is a drop-in for
7+//! the reconstruction / reference plane buffers (`FrameEncoder` rec planes, `RefFrame`).
8+
9+use std::ops::{Deref, DerefMut};
10+
11+/// A heap byte buffer guaranteed to start on a 16-byte boundary.
12+#[derive(Clone, Default)]
13+pub struct AlignedBytes {
14+ words: Vec<u128>,
15+ len: usize,
16+}
17+
18+impl AlignedBytes {
19+ /// A zero-filled, 16-byte-aligned buffer of `len` bytes.
20+ pub fn zeroed(len: usize) -> Self {
21+ Self {
22+ words: vec![0u128; (len + 15) / 16],
23+ len,
24+ }
25+ }
26+
27+ pub fn len(&self) -> usize {
28+ self.len
29+ }
30+
31+ pub fn is_empty(&self) -> bool {
32+ self.len == 0
33+ }
34+}
35+
36+impl std::fmt::Debug for AlignedBytes {
37+ fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
38+ write!(f, "AlignedBytes({} bytes)", self.len)
39+ }
40+}
41+
42+impl Deref for AlignedBytes {
43+ type Target = [u8];
44+ #[inline]
45+ fn deref(&self) -> &[u8] {
46+ &bytemuck::cast_slice(&self.words)[..self.len]
47+ }
48+}
49+
50+impl DerefMut for AlignedBytes {
51+ #[inline]
52+ fn deref_mut(&mut self) -> &mut [u8] {
53+ &mut bytemuck::cast_slice_mut(&mut self.words)[..self.len]
54+ }
55+}
vendor/rusty_h264-common/src/bit_reader.rsadded+343 -0
@@ -0,0 +1,343 @@
1+//! MSB-first bit reader with H.264 Exp-Golomb decoding.
2+//!
3+//! The inverse of [`crate::BitWriter`]. Operates over an RBSP byte slice
4+//! (emulation-prevention bytes already removed — see [`crate::nal`]).
5+
6+/// Error returned when a read runs past the end of the buffer.
7+#[derive(Debug, Clone, Copy, PartialEq, Eq)]
8+pub struct OutOfData;
9+
10+impl core::fmt::Display for OutOfData {
11+ fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
12+ f.write_str("bit reader ran out of data")
13+ }
14+}
15+
16+impl std::error::Error for OutOfData {}
17+
18+/// A big-endian, MSB-first bit reader.
19+#[derive(Debug, Clone)]
20+pub struct BitReader<'a> {
21+ data: &'a [u8],
22+ /// Absolute bit position from the start of `data`.
23+ pos: usize,
24+}
25+
26+impl<'a> BitReader<'a> {
27+ /// Wraps an RBSP byte slice.
28+ pub fn new(data: &'a [u8]) -> Self {
29+ Self { data, pos: 0 }
30+ }
31+
32+ /// The underlying RBSP buffer (for handing off to the CABAC engine).
33+ pub fn data(&self) -> &'a [u8] {
34+ self.data
35+ }
36+
37+ /// Current bit position.
38+ pub fn bit_pos(&self) -> usize {
39+ self.pos
40+ }
41+
42+ /// Total number of bits in the buffer.
43+ pub fn bit_len(&self) -> usize {
44+ self.data.len() * 8
45+ }
46+
47+ /// Bits remaining.
48+ pub fn bits_left(&self) -> usize {
49+ self.bit_len().saturating_sub(self.pos)
50+ }
51+
52+ /// `more_rbsp_data()` (spec §7.2): true while the read position is before the
53+ /// `rbsp_stop_one_bit` (the last set bit in the buffer). Used to detect the
54+ /// end of `slice_data()` when a picture is split into multiple slices.
55+ pub fn more_rbsp_data(&self) -> bool {
56+ // Stop bit = the last 1 bit in the buffer; in MSB-first order that is the
57+ // lowest set bit of the last non-zero byte.
58+ let stop = self
59+ .data
60+ .iter()
61+ .enumerate()
62+ .rev()
63+ .find(|(_, &b)| b != 0)
64+ .map(|(bi, &b)| bi * 8 + (7 - b.trailing_zeros() as usize));
65+ match stop {
66+ Some(s) => self.pos < s,
67+ None => false,
68+ }
69+ }
70+
71+ /// `true` if the read position sits on a byte boundary.
72+ pub fn is_byte_aligned(&self) -> bool {
73+ self.pos % 8 == 0
74+ }
75+
76+ /// Advances to the next byte boundary, consuming the intervening bits (e.g.
77+ /// `pcm_alignment_zero_bit`s before an `I_PCM` payload).
78+ pub fn align_to_byte(&mut self) -> Result<(), OutOfData> {
79+ while self.pos % 8 != 0 {
80+ self.read_bit()?;
81+ }
82+ Ok(())
83+ }
84+
85+ /// Reads a single bit.
86+ pub fn read_bit(&mut self) -> Result<bool, OutOfData> {
87+ if self.pos >= self.bit_len() {
88+ return Err(OutOfData);
89+ }
90+ let byte = self.data[self.pos / 8];
91+ let bit = (byte >> (7 - (self.pos % 8))) & 1;
92+ self.pos += 1;
93+ Ok(bit == 1)
94+ }
95+
96+ /// Reads `n` bits (`n` <= 32) as an unsigned value, MSB first. `u(n)`.
97+ pub fn read_bits(&mut self, n: u32) -> Result<u32, OutOfData> {
98+ // More than 32 bits cannot fit a u32. Rather than panic on a hostile
99+ // length (e.g. a corrupt log2_* field driving the count), reject it.
100+ if n > 32 {
101+ return Err(OutOfData);
102+ }
103+ if n == 0 {
104+ return Ok(0);
105+ }
106+ if n <= 24 {
107+ let v = self.peek_bits(n);
108+ self.skip_bits(n)?;
109+ return Ok(v);
110+ }
111+ // n in 25..=32: two chunks (peek_bits caps at 24).
112+ let hi = self.read_bits(n - 16)?;
113+ let lo = self.read_bits(16)?;
114+ Ok((hi << 16) | lo)
115+ }
116+
117+ /// Peeks the next `n` bits (`n` ≤ 24) as an MSB-first value **without
118+ /// consuming**, zero-filling past the end of the buffer. O(1): loads up to 4
119+ /// bytes. The zero-fill lets a VLC/Exp-Golomb table match be attempted at the
120+ /// stream end; the caller then [`skip_bits`](Self::skip_bits)s the matched
121+ /// length, which rejects (OutOfData) if those bits ran past the buffer.
122+ #[inline]
123+ pub fn peek_bits(&self, n: u32) -> u32 {
124+ debug_assert!(n <= 24);
125+ let byte = self.pos / 8;
126+ let off = (self.pos % 8) as u32;
127+ // 4 bytes (zero past end), MSB-first, into a 32-bit window.
128+ //
129+ // FAST PATH: one RANGE check and one 4-byte big-endian load, which LLVM
130+ // lowers to `mov` + `bswap`. The previous form did FOUR separate
131+ // bounds-checked `get().unwrap_or(&0)` loads plus three shifts and three ORs,
132+ // on a function the entropy decoder calls tens of millions of times per
133+ // sequence. No `unsafe` needed — `get(range)` + `from_be_bytes` is safe and
134+ // compiles to the same thing an unchecked load would.
135+ //
136+ // The slow arm keeps the EXACT zero-fill-past-the-end contract the doc
137+ // comment promises (and that VLC matching at stream end relies on), so the
138+ // two arms are indistinguishable to every caller; `peek_bits_tail_matches`
139+ // pins that across the whole boundary region.
140+ let acc = match self.data.get(byte..byte + 4) {
141+ Some(c) => u32::from_be_bytes([c[0], c[1], c[2], c[3]]),
142+ None => {
143+ ((*self.data.get(byte).unwrap_or(&0) as u32) << 24)
144+ | ((*self.data.get(byte + 1).unwrap_or(&0) as u32) << 16)
145+ | ((*self.data.get(byte + 2).unwrap_or(&0) as u32) << 8)
146+ | (*self.data.get(byte + 3).unwrap_or(&0) as u32)
147+ }
148+ };
149+ // The bit at `pos` is window bit (31 − off); take the `n` bits below it.
150+ (acc >> (32 - off - n)) & ((1u32 << n) - 1)
151+ }
152+
153+ /// Consumes `n` bits (advances the position), after a [`peek_bits`]. Rejects
154+ /// if the bits run past the end of the buffer — the truncated-stream guard
155+ /// that `read_bit`'s per-bit bounds check provided.
156+ #[inline]
157+ pub fn skip_bits(&mut self, n: u32) -> Result<(), OutOfData> {
158+ if self.pos + n as usize > self.bit_len() {
159+ return Err(OutOfData);
160+ }
161+ self.pos += n as usize;
162+ Ok(())
163+ }
164+
165+ /// Unsigned Exp-Golomb decode, `ue(v)`.
166+ pub fn read_ue(&mut self) -> Result<u32, OutOfData> {
167+ // Fast path: a codeword with `lz` leading zeros is `2·lz+1` bits. With
168+ // `lz ≤ 11` the whole codeword fits the 24-bit peek window — find `lz`
169+ // by counting leading zeros, then extract value in one shot.
170+ let window = self.peek_bits(24);
171+ let lz = window.leading_zeros() - 8; // leading zeros within the 24-bit window
172+ if lz <= 11 {
173+ let total = 2 * lz + 1;
174+ self.skip_bits(total)?;
175+ if lz == 0 {
176+ return Ok(0);
177+ }
178+ let info = (window >> (24 - total)) & ((1u32 << lz) - 1);
179+ return Ok((1u32 << lz) - 1 + info);
180+ }
181+ // ≥12 leading zeros (huge value or run of zeros): exact bit-at-a-time.
182+ let mut leading_zeros = 0u32;
183+ while !self.read_bit()? {
184+ leading_zeros += 1;
185+ // 32 leading zeros would make `1 << leading_zeros` overflow u32 (and
186+ // the value is not representable anyway) — reject as malformed.
187+ if leading_zeros >= 32 {
188+ return Err(OutOfData);
189+ }
190+ }
191+ if leading_zeros == 0 {
192+ return Ok(0);
193+ }
194+ let info = self.read_bits(leading_zeros)?;
195+ Ok((1u32 << leading_zeros) - 1 + info)
196+ }
197+
198+ /// Signed Exp-Golomb decode, `se(v)`.
199+ pub fn read_se(&mut self) -> Result<i32, OutOfData> {
200+ let code_num = self.read_ue()?;
201+ // Inverse of the se->code_num mapping.
202+ let magnitude = code_num.div_ceil(2) as i32;
203+ Ok(if code_num % 2 == 1 { magnitude } else { -magnitude })
204+ }
205+}
206+
207+#[cfg(test)]
208+mod tests {
209+ use super::*;
210+ use crate::BitWriter;
211+
212+/// The one-load fast path must equal the byte-at-a-time zero-fill reference at
213+ /// EVERY bit position and width — including the last bytes, where the fast arm
214+ /// stops applying and the tail arm takes over. A mismatch there would corrupt
215+ /// VLC matching only at stream end, which is exactly the bug a mid-buffer test
216+ /// would miss.
217+ #[test]
218+ fn peek_bits_matches_zero_fill_reference() {
219+ fn reference(data: &[u8], pos: usize, n: u32) -> u32 {
220+ let byte = pos / 8;
221+ let off = (pos % 8) as u32;
222+ let acc = ((*data.get(byte).unwrap_or(&0) as u32) << 24)
223+ | ((*data.get(byte + 1).unwrap_or(&0) as u32) << 16)
224+ | ((*data.get(byte + 2).unwrap_or(&0) as u32) << 8)
225+ | (*data.get(byte + 3).unwrap_or(&0) as u32);
226+ (acc >> (32 - off - n)) & ((1u32 << n) - 1)
227+ }
228+ let mut st = 0x1234_5678u32;
229+ let mut rnd = || {
230+ st ^= st << 13;
231+ st ^= st >> 17;
232+ st ^= st << 5;
233+ st
234+ };
235+ for len in 1..24usize {
236+ let data: Vec<u8> = (0..len).map(|_| (rnd() >> 7) as u8).collect();
237+ let r = BitReader::new(&data);
238+ for pos in 0..len * 8 {
239+ for n in 1..=24u32 {
240+ let mut br = BitReader::new(&data);
241+ br.skip_bits(pos as u32).ok();
242+ // skip_bits refuses past the end; drive `pos` directly instead.
243+ let mut probe = BitReader::new(&data);
244+ while probe.bit_pos() < pos {
245+ if probe.read_bit().is_err() {
246+ break;
247+ }
248+ }
249+ if probe.bit_pos() != pos {
250+ continue;
251+ }
252+ assert_eq!(
253+ probe.peek_bits(n),
254+ reference(&data, pos, n),
255+ "len={len} pos={pos} n={n}"
256+ );
257+ }
258+ }
259+ let _ = r;
260+ }
261+ }
262+
263+ #[test]
264+ fn roundtrip_ue() {
265+ for v in [0u32, 1, 2, 3, 4, 7, 8, 255, 256, 65535, u32::MAX - 1] {
266+ let mut w = BitWriter::new();
267+ w.write_ue(v);
268+ w.align_zero();
269+ let bytes = w.into_bytes();
270+ let mut r = BitReader::new(&bytes);
271+ assert_eq!(r.read_ue().unwrap(), v, "ue roundtrip {v}");
272+ }
273+ }
274+
275+ #[test]
276+ fn roundtrip_se() {
277+ for v in [0i32, 1, -1, 2, -2, 100, -100, 32767, -32768] {
278+ let mut w = BitWriter::new();
279+ w.write_se(v);
280+ w.align_zero();
281+ let bytes = w.into_bytes();
282+ let mut r = BitReader::new(&bytes);
283+ assert_eq!(r.read_se().unwrap(), v, "se roundtrip {v}");
284+ }
285+ }
286+
287+ #[test]
288+ fn roundtrip_mixed_stream() {
289+ let mut w = BitWriter::new();
290+ w.write_bits(0b1011, 4);
291+ w.write_ue(42);
292+ w.write_se(-17);
293+ w.write_bits(1, 1);
294+ w.align_zero();
295+ let bytes = w.into_bytes();
296+
297+ let mut r = BitReader::new(&bytes);
298+ assert_eq!(r.read_bits(4).unwrap(), 0b1011);
299+ assert_eq!(r.read_ue().unwrap(), 42);
300+ assert_eq!(r.read_se().unwrap(), -17);
301+ assert_eq!(r.read_bits(1).unwrap(), 1);
302+ }
303+
304+ #[test]
305+ fn reports_out_of_data() {
306+ let bytes = [0x80u8];
307+ let mut r = BitReader::new(&bytes);
308+ assert_eq!(r.read_bits(8).unwrap(), 0x80);
309+ assert_eq!(r.read_bit(), Err(OutOfData));
310+ }
311+
312+ #[test]
313+ fn peek_then_skip_matches_read_bits() {
314+ let bytes = [0xB5u8, 0x3C, 0xF0, 0x0A, 0x77];
315+ // At every bit offset and width, peek_bits + skip_bits must equal a
316+ // consuming read_bits from a fresh reader at the same position.
317+ for start in 0..16u32 {
318+ for n in 1..=24u32 {
319+ let mut a = BitReader::new(&bytes);
320+ a.skip_bits(start).unwrap();
321+ let peeked = a.peek_bits(n);
322+ let pos_before = a.bit_pos();
323+ a.skip_bits(n).unwrap();
324+ assert_eq!(a.bit_pos(), pos_before + n as usize);
325+
326+ let mut b = BitReader::new(&bytes);
327+ b.skip_bits(start).unwrap();
328+ assert_eq!(peeked, b.read_bits(n).unwrap(), "start={start} n={n}");
329+ }
330+ }
331+ }
332+
333+ #[test]
334+ fn peek_zero_fills_past_end() {
335+ let bytes = [0xFFu8];
336+ let mut r = BitReader::new(&bytes);
337+ r.skip_bits(4).unwrap();
338+ // 4 real bits (1111) then zero-fill: 0b1111_0000_0000... for 12 bits.
339+ assert_eq!(r.peek_bits(12), 0b1111_0000_0000);
340+ // skipping past the end is rejected.
341+ assert_eq!(r.skip_bits(8), Err(OutOfData));
342+ }
343+}
vendor/rusty_h264-common/src/bit_writer.rsadded+319 -0
@@ -0,0 +1,319 @@
1+//! MSB-first bit writer with H.264 Exp-Golomb coding.
2+//!
3+//! H.264 packs syntax elements as a big-endian bitstream: the first bit written
4+//! lands in the most-significant position of the first byte. This writer
5+//! accumulates bits and exposes the Exp-Golomb (`ue`/`se`) and fixed-length
6+//! (`u`) codings the bitstream syntax is built from.
7+
8+/// A growable, MSB-first bit buffer.
9+///
10+/// Uses a **bit cache**: bits accumulate in the low `nbits` positions of a 64-bit
11+/// `cache` (the most-recently-written bit is least-significant within the valid
12+/// region), and whole bytes are flushed off the top. A multi-bit write is a shift
13+/// + OR + a short byte-flush loop — not one operation per bit. After every public
14+/// write the invariant `nbits < 8` and "bits above `nbits` are zero" hold.
15+#[derive(Debug, Default, Clone)]
16+pub struct BitWriter {
17+ /// Completed bytes.
18+ bytes: Vec<u8>,
19+ /// Pending bits, valid in the low `nbits` positions (zero above).
20+ cache: u64,
21+ /// Number of valid pending bits (0..=7 between writes).
22+ nbits: u32,
23+}
24+
25+impl BitWriter {
26+ /// Creates an empty writer.
27+ pub fn new() -> Self {
28+ Self::default()
29+ }
30+
31+ /// Creates a writer with `bytes` pre-reserved — for the per-frame slice writer,
32+ /// so the CAVLC hot loop never pays a `Vec` realloc mid-frame.
33+ pub fn with_capacity(bytes: usize) -> Self {
34+ Self {
35+ bytes: Vec::with_capacity(bytes),
36+ cache: 0,
37+ nbits: 0,
38+ }
39+ }
40+
41+ /// Number of bits written so far.
42+ pub fn bit_len(&self) -> usize {
43+ self.bytes.len() * 8 + self.nbits as usize
44+ }
45+
46+ /// `true` if the writer is on a byte boundary.
47+ pub fn is_byte_aligned(&self) -> bool {
48+ self.nbits % 8 == 0
49+ }
50+
51+ /// Writes the low `n` bits of `value`, most-significant first (`u(n)`). `n` <= 32.
52+ ///
53+ /// Keeps up to 31 pending bits in `cache` and flushes a whole **u32 word** (4
54+ /// bytes) at a time, like openh264's `BsWriteBits` (`WRITE_BE_32`) — a quarter
55+ /// the `Vec` writes of byte-at-a-time flushing.
56+ #[inline]
57+ pub fn write_bits(&mut self, value: u32, n: u32) {
58+ debug_assert!(n <= 32, "write_bits supports up to 32 bits");
59+ if n == 0 {
60+ return;
61+ }
62+ let mask = (1u64 << n) - 1; // n<=32 so 1<<32 fits u64
63+ self.cache = (self.cache << n) | (value as u64 & mask);
64+ self.nbits += n;
65+ if self.nbits >= 32 {
66+ self.nbits -= 32;
67+ let word = (self.cache >> self.nbits) as u32;
68+ self.bytes.extend_from_slice(&word.to_be_bytes());
69+ self.cache &= (1u64 << self.nbits) - 1; // drop the flushed high bits
70+ }
71+ }
72+
73+ /// Writes a single bit (`true` => 1).
74+ #[inline]
75+ pub fn write_bit(&mut self, bit: bool) {
76+ self.write_bits(bit as u32, 1);
77+ }
78+
79+ /// Appends every bit of `other`, in order, at this writer's current position.
80+ ///
81+ /// Neither writer need be byte-aligned. This is what lets a macroblock be
82+ /// encoded into a scratch writer *before* the syntax that must precede it is
83+ /// known (`mb_skip_run` is only decided once the macroblock's own cost is), so
84+ /// the encoder can commit one encode rather than trialing and repeating it.
85+ /// Sound for CAVLC because a macroblock's Exp-Golomb/VLC syntax does not depend
86+ /// on its bit position; an arithmetic coder (CABAC) could NOT be spliced this
87+ /// way, since its state is carried across the whole slice.
88+ pub fn append(&mut self, other: &BitWriter) {
89+ for chunk in other.bytes.chunks(4) {
90+ let mut word = 0u32;
91+ for &b in chunk {
92+ word = (word << 8) | b as u32;
93+ }
94+ self.write_bits(word, chunk.len() as u32 * 8);
95+ }
96+ if other.nbits > 0 {
97+ // `cache` holds `nbits` (<= 31) valid bits in its low positions.
98+ self.write_bits(other.cache as u32, other.nbits);
99+ }
100+ }
101+
102+ /// Emits a value already mapped to its Exp-Golomb code number: `floor(log2 x)`
103+ /// leading zeros then `x` in `floor(log2 x)+1` bits, where `x = code_num + 1`.
104+ #[inline]
105+ fn put_golomb(&mut self, x: u64) {
106+ let n = 63 - x.leading_zeros(); // floor(log2 x), 0..=32
107+ self.write_bits(0, n);
108+ if n < 32 {
109+ self.write_bits(x as u32, n + 1);
110+ } else {
111+ // n == 32 (e.g. ue(u32::MAX)): 33-bit value, split across two writes.
112+ self.write_bits((x >> 32) as u32, n - 31);
113+ self.write_bits(x as u32, 32);
114+ }
115+ }
116+
117+ /// Unsigned Exp-Golomb code `ue(v)`.
118+ pub fn write_ue(&mut self, value: u32) {
119+ self.put_golomb(value as u64 + 1);
120+ }
121+
122+ /// Signed Exp-Golomb code `se(v)`: `0->0, 1->1, -1->2, 2->3, -2->4, ...`.
123+ pub fn write_se(&mut self, value: i32) {
124+ let code_num = if value <= 0 {
125+ (-(value as i64) as u64) * 2
126+ } else {
127+ (value as u64) * 2 - 1
128+ };
129+ self.put_golomb(code_num + 1);
130+ }
131+
132+ /// Writes the `rbsp_trailing_bits()`: a stop bit `1` then zero-pad to a byte.
133+ pub fn rbsp_trailing_bits(&mut self) {
134+ self.write_bits(1, 1);
135+ self.align_zero();
136+ }
137+
138+ /// Pads with zero bits to the next byte boundary (no stop bit), then flushes
139+ /// the pending whole bytes from the cache (the word-flush in `write_bits` can
140+ /// leave up to 31 pending bits).
141+ pub fn align_zero(&mut self) {
142+ let pad = (8 - self.nbits % 8) % 8;
143+ if pad != 0 {
144+ self.write_bits(0, pad);
145+ }
146+ while self.nbits >= 8 {
147+ self.nbits -= 8;
148+ self.bytes.push((self.cache >> self.nbits) as u8);
149+ }
150+ self.cache = 0;
151+ }
152+
153+ /// Consumes the writer, returning the byte buffer. Flushes any whole bytes
154+ /// still pending in the cache; panics if a sub-byte remainder is left (call
155+ /// [`rbsp_trailing_bits`](Self::rbsp_trailing_bits) or
156+ /// [`align_zero`](Self::align_zero) first).
157+ pub fn into_bytes(mut self) -> Vec<u8> {
158+ while self.nbits >= 8 {
159+ self.nbits -= 8;
160+ self.bytes.push((self.cache >> self.nbits) as u8);
161+ }
162+ assert!(
163+ self.nbits == 0,
164+ "BitWriter::into_bytes called with {} dangling bits",
165+ self.nbits
166+ );
167+ self.bytes
168+ }
169+
170+ /// Borrows the completed bytes (excludes bits still pending in the cache).
171+ pub fn as_bytes(&self) -> &[u8] {
172+ &self.bytes
173+ }
174+}
175+
176+#[cfg(test)]
177+mod tests {
178+ use super::*;
179+
180+ #[test]
181+ fn write_bits_is_msb_first() {
182+ let mut w = BitWriter::new();
183+ w.write_bits(0b101, 3);
184+ w.write_bits(0b1, 1);
185+ w.align_zero();
186+ // bits 1,0,1,1 then zero-pad -> 1011_0000
187+ assert_eq!(w.into_bytes(), vec![0b1011_0000]);
188+ }
189+
190+ #[test]
191+ fn ue_known_values() {
192+ // From H.264 Table 9-2: code_num -> bit string.
193+ let cases: &[(u32, &str)] = &[
194+ (0, "1"),
195+ (1, "010"),
196+ (2, "011"),
197+ (3, "00100"),
198+ (4, "00101"),
199+ (5, "00110"),
200+ (6, "00111"),
201+ (7, "0001000"),
202+ (8, "0001001"),
203+ ];
204+ for &(v, bits) in cases {
205+ let mut w = BitWriter::new();
206+ w.write_ue(v);
207+ assert_eq!(bitstring(&w), bits, "ue({v})");
208+ }
209+ }
210+
211+ #[test]
212+ fn se_known_values() {
213+ // H.264 Table 9-3 mapping: se -> code_num.
214+ let cases: &[(i32, &str)] = &[
215+ (0, "1"), // code_num 0
216+ (1, "010"), // 1
217+ (-1, "011"), // 2
218+ (2, "00100"),
219+ (-2, "00101"),
220+ (3, "00110"),
221+ (-3, "00111"),
222+ ];
223+ for &(v, bits) in cases {
224+ let mut w = BitWriter::new();
225+ w.write_se(v);
226+ assert_eq!(bitstring(&w), bits, "se({v})");
227+ }
228+ }
229+
230+ #[test]
231+ fn ue_max_does_not_overflow() {
232+ let mut w = BitWriter::new();
233+ w.write_ue(u32::MAX);
234+ // value+1 = 2^32 -> 32 leading zeros then 33-bit value => 65 bits total.
235+ assert_eq!(w.bit_len(), 65);
236+ }
237+
238+ #[test]
239+ fn rbsp_trailing_aligns_to_byte() {
240+ let mut w = BitWriter::new();
241+ w.write_bits(0b101, 3);
242+ w.rbsp_trailing_bits();
243+ // 101 + stop 1 + pad 0000 => 1011_0000
244+ assert_eq!(w.into_bytes(), vec![0b1011_0000]);
245+ }
246+
247+ /// Renders the bits currently buffered (including the partial byte) as a
248+ /// string of '0'/'1' for assertions.
249+ fn bitstring(w: &BitWriter) -> String {
250+ let mut s = String::new();
251+ for &b in w.as_bytes() {
252+ for i in (0..8).rev() {
253+ s.push(if (b >> i) & 1 == 1 { '1' } else { '0' });
254+ }
255+ }
256+ for i in (0..w.nbits).rev() {
257+ s.push(if (w.cache >> i) & 1 == 1 { '1' } else { '0' });
258+ }
259+ s
260+ }
261+}
262+
263+#[cfg(test)]
264+mod append_tests {
265+ use super::BitWriter;
266+
267+ /// Appending must be indistinguishable from having written the bits inline,
268+ /// at every source/destination bit misalignment — this is the invariant the
269+ /// encoder's encode-once-and-splice path rests on.
270+ #[test]
271+ fn append_matches_inline_at_every_alignment() {
272+ for lead in 0..17u32 {
273+ for n in 0..40u32 {
274+ let mut inline = BitWriter::new();
275+ inline.write_bits(0b1011_0110, lead.min(8));
276+ if lead > 8 {
277+ inline.write_bits(0x5A5A, lead - 8);
278+ }
279+ let mut spliced = inline.clone();
280+
281+ // the payload, written bit-patterned so order errors show up
282+ let mut scratch = BitWriter::new();
283+ for i in 0..n {
284+ scratch.write_bit(i % 3 == 0);
285+ }
286+ for i in 0..n {
287+ inline.write_bit(i % 3 == 0);
288+ }
289+ spliced.append(&scratch);
290+
291+ assert_eq!(spliced.bit_len(), inline.bit_len(), "lead={lead} n={n}: length");
292+ let (mut a, mut b) = (spliced.clone(), inline.clone());
293+ a.align_zero();
294+ b.align_zero();
295+ assert_eq!(a.into_bytes(), b.into_bytes(), "lead={lead} n={n}: bits");
296+ }
297+ }
298+ }
299+
300+ /// Exp-Golomb payloads across a byte-crossing boundary (the real shape).
301+ #[test]
302+ fn append_preserves_exp_golomb() {
303+ for lead in 0..9u32 {
304+ let mut inline = BitWriter::new();
305+ inline.write_bits(1, lead);
306+ let mut spliced = inline.clone();
307+ let mut scratch = BitWriter::new();
308+ for v in [0u32, 1, 7, 40, 1000, 65535] {
309+ scratch.write_ue(v);
310+ inline.write_ue(v);
311+ }
312+ spliced.append(&scratch);
313+ assert_eq!(spliced.bit_len(), inline.bit_len(), "lead={lead}: length");
314+ spliced.align_zero();
315+ inline.align_zero();
316+ assert_eq!(spliced.into_bytes(), inline.into_bytes(), "lead={lead}");
317+ }
318+ }
319+}
vendor/rusty_h264-common/src/cabac_tables.rsadded+644 -0
@@ -0,0 +1,644 @@
1+//! CABAC tables ported verbatim from openh264 `common_tables.cpp` (spec
2+//! Tables 9-44/9-45 and 9-12..9-33). 460 contexts, 4 init models [I,idc0,idc1,idc2].
3+//! `CTX_NA` sentinels (I-slice-unused contexts) are 0 as in openh264.
4+
5+/// `rangeTabLPS[pStateIdx][(range>>6)&3]` (Table 9-44).
6+pub const RANGE_LPS: [[u8; 4]; 64] = [
7+ [128, 176, 208, 240],
8+ [128, 167, 197, 227],
9+ [128, 158, 187, 216],
10+ [123, 150, 178, 205],
11+ [116, 142, 169, 195],
12+ [111, 135, 160, 185],
13+ [105, 128, 152, 175],
14+ [100, 122, 144, 166],
15+ [95, 116, 137, 158],
16+ [90, 110, 130, 150],
17+ [85, 104, 123, 142],
18+ [81, 99, 117, 135],
19+ [77, 94, 111, 128],
20+ [73, 89, 105, 122],
21+ [69, 85, 100, 116],
22+ [66, 80, 95, 110],
23+ [62, 76, 90, 104],
24+ [59, 72, 86, 99],
25+ [56, 69, 81, 94],
26+ [53, 65, 77, 89],
27+ [51, 62, 73, 85],
28+ [48, 59, 69, 80],
29+ [46, 56, 66, 76],
30+ [43, 53, 63, 72],
31+ [41, 50, 59, 69],
32+ [39, 48, 56, 65],
33+ [37, 45, 54, 62],
34+ [35, 43, 51, 59],
35+ [33, 41, 48, 56],
36+ [32, 39, 46, 53],
37+ [30, 37, 43, 50],
38+ [29, 35, 41, 48],
39+ [27, 33, 39, 45],
40+ [26, 31, 37, 43],
41+ [24, 30, 35, 41],
42+ [23, 28, 33, 39],
43+ [22, 27, 32, 37],
44+ [21, 26, 30, 35],
45+ [20, 24, 29, 33],
46+ [19, 23, 27, 31],
47+ [18, 22, 26, 30],
48+ [17, 21, 25, 28],
49+ [16, 20, 23, 27],
50+ [15, 19, 22, 25],
51+ [14, 18, 21, 24],
52+ [14, 17, 20, 23],
53+ [13, 16, 19, 22],
54+ [12, 15, 18, 21],
55+ [12, 14, 17, 20],
56+ [11, 14, 16, 19],
57+ [11, 13, 15, 18],
58+ [10, 12, 15, 17],
59+ [10, 12, 14, 16],
60+ [9, 11, 13, 15],
61+ [9, 11, 12, 14],
62+ [8, 10, 12, 14],
63+ [8, 9, 11, 13],
64+ [7, 9, 11, 12],
65+ [7, 9, 10, 12],
66+ [7, 8, 10, 11],
67+ [6, 8, 9, 11],
68+ [6, 7, 9, 10],
69+ [6, 7, 8, 9],
70+ [2, 2, 2, 2],
71+];
72+
73+/// State transition `[pStateIdx] -> [transIdxLPS, transIdxMPS]` (Table 9-45).
74+pub const STATE_TRANS: [[u8; 2]; 64] = [
75+ [0, 1],
76+ [0, 2],
77+ [1, 3],
78+ [2, 4],
79+ [2, 5],
80+ [4, 6],
81+ [4, 7],
82+ [5, 8],
83+ [6, 9],
84+ [7, 10],
85+ [8, 11],
86+ [9, 12],
87+ [9, 13],
88+ [11, 14],
89+ [11, 15],
90+ [12, 16],
91+ [13, 17],
92+ [13, 18],
93+ [15, 19],
94+ [15, 20],
95+ [16, 21],
96+ [16, 22],
97+ [18, 23],
98+ [18, 24],
99+ [19, 25],
100+ [19, 26],
101+ [21, 27],
102+ [21, 28],
103+ [22, 29],
104+ [22, 30],
105+ [23, 31],
106+ [24, 32],
107+ [24, 33],
108+ [25, 34],
109+ [26, 35],
110+ [26, 36],
111+ [27, 37],
112+ [27, 38],
113+ [28, 39],
114+ [29, 40],
115+ [29, 41],
116+ [30, 42],
117+ [30, 43],
118+ [30, 44],
119+ [31, 45],
120+ [32, 46],
121+ [32, 47],
122+ [33, 48],
123+ [33, 49],
124+ [33, 50],
125+ [34, 51],
126+ [34, 52],
127+ [35, 53],
128+ [35, 54],
129+ [35, 55],
130+ [36, 56],
131+ [36, 57],
132+ [36, 58],
133+ [37, 59],
134+ [37, 60],
135+ [37, 61],
136+ [38, 62],
137+ [38, 62],
138+ [63, 63],
139+];
140+
141+/// Context init `(m, n)` per `[ctxIdx][model]` (model 0=I, 1..=3 = init_idc 0..2).
142+pub const CTX_INIT: [[(i16, i16); 4]; 460] = [
143+ [(20, -15), (20, -15), (20, -15), (20, -15)],
144+ [(2, 54), (2, 54), (2, 54), (2, 54)],
145+ [(3, 74), (3, 74), (3, 74), (3, 74)],
146+ [(20, -15), (20, -15), (20, -15), (20, -15)],
147+ [(2, 54), (2, 54), (2, 54), (2, 54)],
148+ [(3, 74), (3, 74), (3, 74), (3, 74)],
149+ [(-28, 127), (-28, 127), (-28, 127), (-28, 127)],
150+ [(-23, 104), (-23, 104), (-23, 104), (-23, 104)],
151+ [(-6, 53), (-6, 53), (-6, 53), (-6, 53)],
152+ [(-1, 54), (-1, 54), (-1, 54), (-1, 54)],
153+ [(7, 51), (7, 51), (7, 51), (7, 51)],
154+ [(0, 0), (23, 33), (22, 25), (29, 16)],
155+ [(0, 0), (23, 2), (34, 0), (25, 0)],
156+ [(0, 0), (21, 0), (16, 0), (14, 0)],
157+ [(0, 0), (1, 9), (-2, 9), (-10, 51)],
158+ [(0, 0), (0, 49), (4, 41), (-3, 62)],
159+ [(0, 0), (-37, 118), (-29, 118), (-27, 99)],
160+ [(0, 0), (5, 57), (2, 65), (26, 16)],
161+ [(0, 0), (-13, 78), (-6, 71), (-4, 85)],
162+ [(0, 0), (-11, 65), (-13, 79), (-24, 102)],
163+ [(0, 0), (1, 62), (5, 52), (5, 57)],
164+ [(0, 0), (12, 49), (9, 50), (6, 57)],
165+ [(0, 0), (-4, 73), (-3, 70), (-17, 73)],
166+ [(0, 0), (17, 50), (10, 54), (14, 57)],
167+ [(0, 0), (18, 64), (26, 34), (20, 40)],
168+ [(0, 0), (9, 43), (19, 22), (20, 10)],
169+ [(0, 0), (29, 0), (40, 0), (29, 0)],
170+ [(0, 0), (26, 67), (57, 2), (54, 0)],
171+ [(0, 0), (16, 90), (41, 36), (37, 42)],
172+ [(0, 0), (9, 104), (26, 69), (12, 97)],
173+ [(0, 0), (-46, 127), (-45, 127), (-32, 127)],
174+ [(0, 0), (-20, 104), (-15, 101), (-22, 117)],
175+ [(0, 0), (1, 67), (-4, 76), (-2, 74)],
176+ [(0, 0), (-13, 78), (-6, 71), (-4, 85)],
177+ [(0, 0), (-11, 65), (-13, 79), (-24, 102)],
178+ [(0, 0), (1, 62), (5, 52), (5, 57)],
179+ [(0, 0), (-6, 86), (6, 69), (-6, 93)],
180+ [(0, 0), (-17, 95), (-13, 90), (-14, 88)],
181+ [(0, 0), (-6, 61), (0, 52), (-6, 44)],
182+ [(0, 0), (9, 45), (8, 43), (4, 55)],
183+ [(0, 0), (-3, 69), (-2, 69), (-11, 89)],
184+ [(0, 0), (-6, 81), (-5, 82), (-15, 103)],
185+ [(0, 0), (-11, 96), (-10, 96), (-21, 116)],
186+ [(0, 0), (6, 55), (2, 59), (19, 57)],
187+ [(0, 0), (7, 67), (2, 75), (20, 58)],
188+ [(0, 0), (-5, 86), (-3, 87), (4, 84)],
189+ [(0, 0), (2, 88), (-3, 100), (6, 96)],
190+ [(0, 0), (0, 58), (1, 56), (1, 63)],
191+ [(0, 0), (-3, 76), (-3, 74), (-5, 85)],
192+ [(0, 0), (-10, 94), (-6, 85), (-13, 106)],
193+ [(0, 0), (5, 54), (0, 59), (5, 63)],
194+ [(0, 0), (4, 69), (-3, 81), (6, 75)],
195+ [(0, 0), (-3, 81), (-7, 86), (-3, 90)],
196+ [(0, 0), (0, 88), (-5, 95), (-1, 101)],
197+ [(0, 0), (-7, 67), (-1, 66), (3, 55)],
198+ [(0, 0), (-5, 74), (-1, 77), (-4, 79)],
199+ [(0, 0), (-4, 74), (1, 70), (-2, 75)],
200+ [(0, 0), (-5, 80), (-2, 86), (-12, 97)],
201+ [(0, 0), (-7, 72), (-5, 72), (-7, 50)],
202+ [(0, 0), (1, 58), (0, 61), (1, 60)],
203+ [(0, 41), (0, 41), (0, 41), (0, 41)],
204+ [(0, 63), (0, 63), (0, 63), (0, 63)],
205+ [(0, 63), (0, 63), (0, 63), (0, 63)],
206+ [(0, 63), (0, 63), (0, 63), (0, 63)],
207+ [(-9, 83), (-9, 83), (-9, 83), (-9, 83)],
208+ [(4, 86), (4, 86), (4, 86), (4, 86)],
209+ [(0, 97), (0, 97), (0, 97), (0, 97)],
210+ [(-7, 72), (-7, 72), (-7, 72), (-7, 72)],
211+ [(13, 41), (13, 41), (13, 41), (13, 41)],
212+ [(3, 62), (3, 62), (3, 62), (3, 62)],
213+ [(0, 11), (0, 45), (13, 15), (7, 34)],
214+ [(1, 55), (-4, 78), (7, 51), (-9, 88)],
215+ [(0, 69), (-3, 96), (2, 80), (-20, 127)],
216+ [(-17, 127), (-27, 126), (-39, 127), (-36, 127)],
217+ [(-13, 102), (-28, 98), (-18, 91), (-17, 91)],
218+ [(0, 82), (-25, 101), (-17, 96), (-14, 95)],
219+ [(-7, 74), (-23, 67), (-26, 81), (-25, 84)],
220+ [(-21, 107), (-28, 82), (-35, 98), (-25, 86)],
221+ [(-27, 127), (-20, 94), (-24, 102), (-12, 89)],
222+ [(-31, 127), (-16, 83), (-23, 97), (-17, 91)],
223+ [(-24, 127), (-22, 110), (-27, 119), (-31, 127)],
224+ [(-18, 95), (-21, 91), (-24, 99), (-14, 76)],
225+ [(-27, 127), (-18, 102), (-21, 110), (-18, 103)],
226+ [(-21, 114), (-13, 93), (-18, 102), (-13, 90)],
227+ [(-30, 127), (-29, 127), (-36, 127), (-37, 127)],
228+ [(-17, 123), (-7, 92), (0, 80), (11, 80)],
229+ [(-12, 115), (-5, 89), (-5, 89), (5, 76)],
230+ [(-16, 122), (-7, 96), (-7, 94), (2, 84)],
231+ [(-11, 115), (-13, 108), (-4, 92), (5, 78)],
232+ [(-12, 63), (-3, 46), (0, 39), (-6, 55)],
233+ [(-2, 68), (-1, 65), (0, 65), (4, 61)],
234+ [(-15, 84), (-1, 57), (-15, 84), (-14, 83)],
235+ [(-13, 104), (-9, 93), (-35, 127), (-37, 127)],
236+ [(-3, 70), (-3, 74), (-2, 73), (-5, 79)],
237+ [(-8, 93), (-9, 92), (-12, 104), (-11, 104)],
238+ [(-10, 90), (-8, 87), (-9, 91), (-11, 91)],
239+ [(-30, 127), (-23, 126), (-31, 127), (-30, 127)],
240+ [(-1, 74), (5, 54), (3, 55), (0, 65)],
241+ [(-6, 97), (6, 60), (7, 56), (-2, 79)],
242+ [(-7, 91), (6, 59), (7, 55), (0, 72)],
243+ [(-20, 127), (6, 69), (8, 61), (-4, 92)],
244+ [(-4, 56), (-1, 48), (-3, 53), (-6, 56)],
245+ [(-5, 82), (0, 68), (0, 68), (3, 68)],
246+ [(-7, 76), (-4, 69), (-7, 74), (-8, 71)],
247+ [(-22, 125), (-8, 88), (-9, 88), (-13, 98)],
248+ [(-7, 93), (-2, 85), (-13, 103), (-4, 86)],
249+ [(-11, 87), (-6, 78), (-13, 91), (-12, 88)],
250+ [(-3, 77), (-1, 75), (-9, 89), (-5, 82)],
251+ [(-5, 71), (-7, 77), (-14, 92), (-3, 72)],
252+ [(-4, 63), (2, 54), (-8, 76), (-4, 67)],
253+ [(-4, 68), (5, 50), (-12, 87), (-8, 72)],
254+ [(-12, 84), (-3, 68), (-23, 110), (-16, 89)],
255+ [(-7, 62), (1, 50), (-24, 105), (-9, 69)],
256+ [(-7, 65), (6, 42), (-10, 78), (-1, 59)],
257+ [(8, 61), (-4, 81), (-20, 112), (5, 66)],
258+ [(5, 56), (1, 63), (-17, 99), (4, 57)],
259+ [(-2, 66), (-4, 70), (-78, 127), (-4, 71)],
260+ [(1, 64), (0, 67), (-70, 127), (-2, 71)],
261+ [(0, 61), (2, 57), (-50, 127), (2, 58)],
262+ [(-2, 78), (-2, 76), (-46, 127), (-1, 74)],
263+ [(1, 50), (11, 35), (-4, 66), (-4, 44)],
264+ [(7, 52), (4, 64), (-5, 78), (-1, 69)],
265+ [(10, 35), (1, 61), (-4, 71), (0, 62)],
266+ [(0, 44), (11, 35), (-8, 72), (-7, 51)],
267+ [(11, 38), (18, 25), (2, 59), (-4, 47)],
268+ [(1, 45), (12, 24), (-1, 55), (-6, 42)],
269+ [(0, 46), (13, 29), (-7, 70), (-3, 41)],
270+ [(5, 44), (13, 36), (-6, 75), (-6, 53)],
271+ [(31, 17), (-10, 93), (-8, 89), (8, 76)],
272+ [(1, 51), (-7, 73), (-34, 119), (-9, 78)],
273+ [(7, 50), (-2, 73), (-3, 75), (-11, 83)],
274+ [(28, 19), (13, 46), (32, 20), (9, 52)],
275+ [(16, 33), (9, 49), (30, 22), (0, 67)],
276+ [(14, 62), (-7, 100), (-44, 127), (-5, 90)],
277+ [(-13, 108), (9, 53), (0, 54), (1, 67)],
278+ [(-15, 100), (2, 53), (-5, 61), (-15, 72)],
279+ [(-13, 101), (5, 53), (0, 58), (-5, 75)],
280+ [(-13, 91), (-2, 61), (-1, 60), (-8, 80)],
281+ [(-12, 94), (0, 56), (-3, 61), (-21, 83)],
282+ [(-10, 88), (0, 56), (-8, 67), (-21, 64)],
283+ [(-16, 84), (-13, 63), (-25, 84), (-13, 31)],
284+ [(-10, 86), (-5, 60), (-14, 74), (-25, 64)],
285+ [(-7, 83), (-1, 62), (-5, 65), (-29, 94)],
286+ [(-13, 87), (4, 57), (5, 52), (9, 75)],
287+ [(-19, 94), (-6, 69), (2, 57), (17, 63)],
288+ [(1, 70), (4, 57), (0, 61), (-8, 74)],
289+ [(0, 72), (14, 39), (-9, 69), (-5, 35)],
290+ [(-5, 74), (4, 51), (-11, 70), (-2, 27)],
291+ [(18, 59), (13, 68), (18, 55), (13, 91)],
292+ [(-8, 102), (3, 64), (-4, 71), (3, 65)],
293+ [(-15, 100), (1, 61), (0, 58), (-7, 69)],
294+ [(0, 95), (9, 63), (7, 61), (8, 77)],
295+ [(-4, 75), (7, 50), (9, 41), (-10, 66)],
296+ [(2, 72), (16, 39), (18, 25), (3, 62)],
297+ [(-11, 75), (5, 44), (9, 32), (-3, 68)],
298+ [(-3, 71), (4, 52), (5, 43), (-20, 81)],
299+ [(15, 46), (11, 48), (9, 47), (0, 30)],
300+ [(-13, 69), (-5, 60), (0, 44), (1, 7)],
301+ [(0, 62), (-1, 59), (0, 51), (-3, 23)],
302+ [(0, 65), (0, 59), (2, 46), (-21, 74)],
303+ [(21, 37), (22, 33), (19, 38), (16, 66)],
304+ [(-15, 72), (5, 44), (-4, 66), (-23, 124)],
305+ [(9, 57), (14, 43), (15, 38), (17, 37)],
306+ [(16, 54), (-1, 78), (12, 42), (44, -18)],
307+ [(0, 62), (0, 60), (9, 34), (50, -34)],
308+ [(12, 72), (9, 69), (0, 89), (-22, 127)],
309+ [(24, 0), (11, 28), (4, 45), (4, 39)],
310+ [(15, 9), (2, 40), (10, 28), (0, 42)],
311+ [(8, 25), (3, 44), (10, 31), (7, 34)],
312+ [(13, 18), (0, 49), (33, -11), (11, 29)],
313+ [(15, 9), (0, 46), (52, -43), (8, 31)],
314+ [(13, 19), (2, 44), (18, 15), (6, 37)],
315+ [(10, 37), (2, 51), (28, 0), (7, 42)],
316+ [(12, 18), (0, 47), (35, -22), (3, 40)],
317+ [(6, 29), (4, 39), (38, -25), (8, 33)],
318+ [(20, 33), (2, 62), (34, 0), (13, 43)],
319+ [(15, 30), (6, 46), (39, -18), (13, 36)],
320+ [(4, 45), (0, 54), (32, -12), (4, 47)],
321+ [(1, 58), (3, 54), (102, -94), (3, 55)],
322+ [(0, 62), (2, 58), (0, 0), (2, 58)],
323+ [(7, 61), (4, 63), (56, -15), (6, 60)],
324+ [(12, 38), (6, 51), (33, -4), (8, 44)],
325+ [(11, 45), (6, 57), (29, 10), (11, 44)],
326+ [(15, 39), (7, 53), (37, -5), (14, 42)],
327+ [(11, 42), (6, 52), (51, -29), (7, 48)],
328+ [(13, 44), (6, 55), (39, -9), (4, 56)],
329+ [(16, 45), (11, 45), (52, -34), (4, 52)],
330+ [(12, 41), (14, 36), (69, -58), (13, 37)],
331+ [(10, 49), (8, 53), (67, -63), (9, 49)],
332+ [(30, 34), (-1, 82), (44, -5), (19, 58)],
333+ [(18, 42), (7, 55), (32, 7), (10, 48)],
334+ [(10, 55), (-3, 78), (55, -29), (12, 45)],
335+ [(17, 51), (15, 46), (32, 1), (0, 69)],
336+ [(17, 46), (22, 31), (0, 0), (20, 33)],
337+ [(0, 89), (-1, 84), (27, 36), (8, 63)],
338+ [(26, -19), (25, 7), (33, -25), (35, -18)],
339+ [(22, -17), (30, -7), (34, -30), (33, -25)],
340+ [(26, -17), (28, 3), (36, -28), (28, -3)],
341+ [(30, -25), (28, 4), (38, -28), (24, 10)],
342+ [(28, -20), (32, 0), (38, -27), (27, 0)],
343+ [(33, -23), (34, -1), (34, -18), (34, -14)],
344+ [(37, -27), (30, 6), (35, -16), (52, -44)],
345+ [(33, -23), (30, 6), (34, -14), (39, -24)],
346+ [(40, -28), (32, 9), (32, -8), (19, 17)],
347+ [(38, -17), (31, 19), (37, -6), (31, 25)],
348+ [(33, -11), (26, 27), (35, 0), (36, 29)],
349+ [(40, -15), (26, 30), (30, 10), (24, 33)],
350+ [(41, -6), (37, 20), (28, 18), (34, 15)],
351+ [(38, 1), (28, 34), (26, 25), (30, 20)],
352+ [(41, 17), (17, 70), (29, 41), (22, 73)],
353+ [(30, -6), (1, 67), (0, 75), (20, 34)],
354+ [(27, 3), (5, 59), (2, 72), (19, 31)],
355+ [(26, 22), (9, 67), (8, 77), (27, 44)],
356+ [(37, -16), (16, 30), (14, 35), (19, 16)],
357+ [(35, -4), (18, 32), (18, 31), (15, 36)],
358+ [(38, -8), (18, 35), (17, 35), (15, 36)],
359+ [(38, -3), (22, 29), (21, 30), (21, 28)],
360+ [(37, 3), (24, 31), (17, 45), (25, 21)],
361+ [(38, 5), (23, 38), (20, 42), (30, 20)],
362+ [(42, 0), (18, 43), (18, 45), (31, 12)],
363+ [(35, 16), (20, 41), (27, 26), (27, 16)],
364+ [(39, 22), (11, 63), (16, 54), (24, 42)],
365+ [(14, 48), (9, 59), (7, 66), (0, 93)],
366+ [(27, 37), (9, 64), (16, 56), (14, 56)],
367+ [(21, 60), (-1, 94), (11, 73), (15, 57)],
368+ [(12, 68), (-2, 89), (10, 67), (26, 38)],
369+ [(2, 97), (-9, 108), (-10, 116), (-24, 127)],
370+ [(-3, 71), (-6, 76), (-23, 112), (-24, 115)],
371+ [(-6, 42), (-2, 44), (-15, 71), (-22, 82)],
372+ [(-5, 50), (0, 45), (-7, 61), (-9, 62)],
373+ [(-3, 54), (0, 52), (0, 53), (0, 53)],
374+ [(-2, 62), (-3, 64), (-5, 66), (0, 59)],
375+ [(0, 58), (-2, 59), (-11, 77), (-14, 85)],
376+ [(1, 63), (-4, 70), (-9, 80), (-13, 89)],
377+ [(-2, 72), (-4, 75), (-9, 84), (-13, 94)],
378+ [(-1, 74), (-8, 82), (-10, 87), (-11, 92)],
379+ [(-9, 91), (-17, 102), (-34, 127), (-29, 127)],
380+ [(-5, 67), (-9, 77), (-21, 101), (-21, 100)],
381+ [(-5, 27), (3, 24), (-3, 39), (-14, 57)],
382+ [(-3, 39), (0, 42), (-5, 53), (-12, 67)],
383+ [(-2, 44), (0, 48), (-7, 61), (-11, 71)],
384+ [(0, 46), (0, 55), (-11, 75), (-10, 77)],
385+ [(-16, 64), (-6, 59), (-15, 77), (-21, 85)],
386+ [(-8, 68), (-7, 71), (-17, 91), (-16, 88)],
387+ [(-10, 78), (-12, 83), (-25, 107), (-23, 104)],
388+ [(-6, 77), (-11, 87), (-25, 111), (-15, 98)],
389+ [(-10, 86), (-30, 119), (-28, 122), (-37, 127)],
390+ [(-12, 92), (1, 58), (-11, 76), (-10, 82)],
391+ [(-15, 55), (-3, 29), (-10, 44), (-8, 48)],
392+ [(-10, 60), (-1, 36), (-10, 52), (-8, 61)],
393+ [(-6, 62), (1, 38), (-10, 57), (-8, 66)],
394+ [(-4, 65), (2, 43), (-9, 58), (-7, 70)],
395+ [(-12, 73), (-6, 55), (-16, 72), (-14, 75)],
396+ [(-8, 76), (0, 58), (-7, 69), (-10, 79)],
397+ [(-7, 80), (0, 64), (-4, 69), (-9, 83)],
398+ [(-9, 88), (-3, 74), (-5, 74), (-12, 92)],
399+ [(-17, 110), (-10, 90), (-9, 86), (-18, 108)],
400+ [(-11, 97), (0, 70), (2, 66), (-4, 79)],
401+ [(-20, 84), (-4, 29), (-9, 34), (-22, 69)],
402+ [(-11, 79), (5, 31), (1, 32), (-16, 75)],
403+ [(-6, 73), (7, 42), (11, 31), (-2, 58)],
404+ [(-4, 74), (1, 59), (5, 52), (1, 58)],
405+ [(-13, 86), (-2, 58), (-2, 55), (-13, 78)],
406+ [(-13, 96), (-3, 72), (-2, 67), (-9, 83)],
407+ [(-11, 97), (-3, 81), (0, 73), (-4, 81)],
408+ [(-19, 117), (-11, 97), (-8, 89), (-13, 99)],
409+ [(-8, 78), (0, 58), (3, 52), (-13, 81)],
410+ [(-5, 33), (8, 5), (7, 4), (-6, 38)],
411+ [(-4, 48), (10, 14), (10, 8), (-13, 62)],
412+ [(-2, 53), (14, 18), (17, 8), (-6, 58)],
413+ [(-3, 62), (13, 27), (16, 19), (-2, 59)],
414+ [(-13, 71), (2, 40), (3, 37), (-16, 73)],
415+ [(-10, 79), (0, 58), (-1, 61), (-10, 76)],
416+ [(-12, 86), (-3, 70), (-5, 73), (-13, 86)],
417+ [(-13, 90), (-6, 79), (-1, 70), (-9, 83)],
418+ [(-14, 97), (-8, 85), (-4, 78), (-10, 87)],
419+ [(0, 0), (0, 0), (0, 0), (0, 0)],
420+ [(-6, 93), (-13, 106), (-21, 126), (-22, 127)],
421+ [(-6, 84), (-16, 106), (-23, 124), (-25, 127)],
422+ [(-8, 79), (-10, 87), (-20, 110), (-25, 120)],
423+ [(0, 66), (-21, 114), (-26, 126), (-27, 127)],
424+ [(-1, 71), (-18, 110), (-25, 124), (-19, 114)],
425+ [(0, 62), (-14, 98), (-17, 105), (-23, 117)],
426+ [(-2, 60), (-22, 110), (-27, 121), (-25, 118)],
427+ [(-2, 59), (-21, 106), (-27, 117), (-26, 117)],
428+ [(-5, 75), (-18, 103), (-17, 102), (-24, 113)],
429+ [(-3, 62), (-21, 107), (-26, 117), (-28, 118)],
430+ [(-4, 58), (-23, 108), (-27, 116), (-31, 120)],
431+ [(-9, 66), (-26, 112), (-33, 122), (-37, 124)],
432+ [(-1, 79), (-10, 96), (-10, 95), (-10, 94)],
433+ [(0, 71), (-12, 95), (-14, 100), (-15, 102)],
434+ [(3, 68), (-5, 91), (-8, 95), (-10, 99)],
435+ [(10, 44), (-9, 93), (-17, 111), (-13, 106)],
436+ [(-7, 62), (-22, 94), (-28, 114), (-50, 127)],
437+ [(15, 36), (-5, 86), (-6, 89), (-5, 92)],
438+ [(14, 40), (9, 67), (-2, 80), (17, 57)],
439+ [(16, 27), (-4, 80), (-4, 82), (-5, 86)],
440+ [(12, 29), (-10, 85), (-9, 85), (-13, 94)],
441+ [(1, 44), (-1, 70), (-8, 81), (-12, 91)],
442+ [(20, 36), (7, 60), (-1, 72), (-2, 77)],
443+ [(18, 32), (9, 58), (5, 64), (0, 71)],
444+ [(5, 42), (5, 61), (1, 67), (-1, 73)],
445+ [(1, 48), (12, 50), (9, 56), (4, 64)],
446+ [(10, 62), (15, 50), (0, 69), (-7, 81)],
447+ [(17, 46), (18, 49), (1, 69), (5, 64)],
448+ [(9, 64), (17, 54), (7, 69), (15, 57)],
449+ [(-12, 104), (10, 41), (-7, 69), (1, 67)],
450+ [(-11, 97), (7, 46), (-6, 67), (0, 68)],
451+ [(-16, 96), (-1, 51), (-16, 77), (-10, 67)],
452+ [(-7, 88), (7, 49), (-2, 64), (1, 68)],
453+ [(-8, 85), (8, 52), (2, 61), (0, 77)],
454+ [(-7, 85), (9, 41), (-6, 67), (2, 64)],
455+ [(-9, 85), (6, 47), (-3, 64), (0, 68)],
456+ [(-13, 88), (2, 55), (2, 57), (-5, 78)],
457+ [(4, 66), (13, 41), (-3, 65), (7, 55)],
458+ [(-3, 77), (10, 44), (-3, 66), (5, 59)],
459+ [(-3, 76), (6, 50), (0, 62), (2, 65)],
460+ [(-6, 76), (5, 53), (9, 51), (14, 54)],
461+ [(10, 58), (13, 49), (-1, 66), (15, 44)],
462+ [(-1, 76), (4, 63), (-2, 71), (5, 60)],
463+ [(-1, 83), (6, 64), (-2, 75), (2, 70)],
464+ [(-7, 99), (-2, 69), (-1, 70), (-2, 76)],
465+ [(-14, 95), (-2, 59), (-9, 72), (-18, 86)],
466+ [(2, 95), (6, 70), (14, 60), (12, 70)],
467+ [(0, 76), (10, 44), (16, 37), (5, 64)],
468+ [(-5, 74), (9, 31), (0, 47), (-12, 70)],
469+ [(0, 70), (12, 43), (18, 35), (11, 55)],
470+ [(-11, 75), (3, 53), (11, 37), (5, 56)],
471+ [(1, 68), (14, 34), (12, 41), (0, 69)],
472+ [(0, 65), (10, 38), (10, 41), (2, 65)],
473+ [(-14, 73), (-3, 52), (2, 48), (-6, 74)],
474+ [(3, 62), (13, 40), (12, 41), (5, 54)],
475+ [(4, 62), (17, 32), (13, 41), (7, 54)],
476+ [(-1, 68), (7, 44), (0, 59), (-6, 76)],
477+ [(-13, 75), (7, 38), (3, 50), (-11, 82)],
478+ [(11, 55), (13, 50), (19, 40), (-2, 77)],
479+ [(5, 64), (10, 57), (3, 66), (-2, 77)],
480+ [(12, 70), (26, 43), (18, 50), (25, 42)],
481+ [(15, 6), (14, 11), (19, -6), (17, -13)],
482+ [(6, 19), (11, 14), (18, -6), (16, -9)],
483+ [(7, 16), (9, 11), (14, 0), (17, -12)],
484+ [(12, 14), (18, 11), (26, -12), (27, -21)],
485+ [(18, 13), (21, 9), (31, -16), (37, -30)],
486+ [(13, 11), (23, -2), (33, -25), (41, -40)],
487+ [(13, 15), (32, -15), (33, -22), (42, -41)],
488+ [(15, 16), (32, -15), (37, -28), (48, -47)],
489+ [(12, 23), (34, -21), (39, -30), (39, -32)],
490+ [(13, 23), (39, -23), (42, -30), (46, -40)],
491+ [(15, 20), (42, -33), (47, -42), (52, -51)],
492+ [(14, 26), (41, -31), (45, -36), (46, -41)],
493+ [(14, 44), (46, -28), (49, -34), (52, -39)],
494+ [(17, 40), (38, -12), (41, -17), (43, -19)],
495+ [(17, 47), (21, 29), (32, 9), (32, 11)],
496+ [(24, 17), (45, -24), (69, -71), (61, -55)],
497+ [(21, 21), (53, -45), (63, -63), (56, -46)],
498+ [(25, 22), (48, -26), (66, -64), (62, -50)],
499+ [(31, 27), (65, -43), (77, -74), (81, -67)],
500+ [(22, 29), (43, -19), (54, -39), (45, -20)],
501+ [(19, 35), (39, -10), (52, -35), (35, -2)],
502+ [(14, 50), (30, 9), (41, -10), (28, 15)],
503+ [(10, 57), (18, 26), (36, 0), (34, 1)],
504+ [(7, 63), (20, 27), (40, -1), (39, 1)],
505+ [(-2, 77), (0, 57), (30, 14), (30, 17)],
506+ [(-4, 82), (-14, 82), (28, 26), (20, 38)],
507+ [(-3, 94), (-5, 75), (23, 37), (18, 45)],
508+ [(9, 69), (-19, 97), (12, 55), (15, 54)],
509+ [(-12, 109), (-35, 125), (11, 65), (0, 79)],
510+ [(36, -35), (27, 0), (37, -33), (36, -16)],
511+ [(36, -34), (28, 0), (39, -36), (37, -14)],
512+ [(32, -26), (31, -4), (40, -37), (37, -17)],
513+ [(37, -30), (27, 6), (38, -30), (32, 1)],
514+ [(44, -32), (34, 8), (46, -33), (34, 15)],
515+ [(34, -18), (30, 10), (42, -30), (29, 15)],
516+ [(34, -15), (24, 22), (40, -24), (24, 25)],
517+ [(40, -15), (33, 19), (49, -29), (34, 22)],
518+ [(33, -7), (22, 32), (38, -12), (31, 16)],
519+ [(35, -5), (26, 31), (40, -10), (35, 18)],
520+ [(33, 0), (21, 41), (38, -3), (31, 28)],
521+ [(38, 2), (26, 44), (46, -5), (33, 41)],
522+ [(33, 13), (23, 47), (31, 20), (36, 28)],
523+ [(23, 35), (16, 65), (29, 30), (27, 47)],
524+ [(13, 58), (14, 71), (25, 44), (21, 62)],
525+ [(29, -3), (8, 60), (12, 48), (18, 31)],
526+ [(26, 0), (6, 63), (11, 49), (19, 26)],
527+ [(22, 30), (17, 65), (26, 45), (36, 24)],
528+ [(31, -7), (21, 24), (22, 22), (24, 23)],
529+ [(35, -15), (23, 20), (23, 22), (27, 16)],
530+ [(34, -3), (26, 23), (27, 21), (24, 30)],
531+ [(34, 3), (27, 32), (33, 20), (31, 29)],
532+ [(36, -1), (28, 23), (26, 28), (22, 41)],
533+ [(34, 5), (28, 24), (30, 24), (22, 42)],
534+ [(32, 11), (23, 40), (27, 34), (16, 60)],
535+ [(35, 5), (24, 32), (18, 42), (15, 52)],
536+ [(34, 12), (28, 29), (25, 39), (14, 60)],
537+ [(39, 11), (23, 42), (18, 50), (3, 78)],
538+ [(30, 29), (19, 57), (12, 70), (-16, 123)],
539+ [(34, 26), (22, 53), (21, 54), (21, 53)],
540+ [(29, 39), (22, 61), (14, 71), (22, 56)],
541+ [(19, 66), (11, 86), (11, 83), (25, 61)],
542+ [(31, 21), (12, 40), (25, 32), (21, 33)],
543+ [(31, 31), (11, 51), (21, 49), (19, 50)],
544+ [(25, 50), (14, 59), (21, 54), (17, 61)],
545+ [(-17, 120), (-4, 79), (-5, 85), (-3, 78)],
546+ [(-20, 112), (-7, 71), (-6, 81), (-8, 74)],
547+ [(-18, 114), (-5, 69), (-10, 77), (-9, 72)],
548+ [(-11, 85), (-9, 70), (-7, 81), (-10, 72)],
549+ [(-15, 92), (-8, 66), (-17, 80), (-18, 75)],
550+ [(-14, 89), (-10, 68), (-18, 73), (-12, 71)],
551+ [(-26, 71), (-19, 73), (-4, 74), (-11, 63)],
552+ [(-15, 81), (-12, 69), (-10, 83), (-5, 70)],
553+ [(-14, 80), (-16, 70), (-9, 71), (-17, 75)],
554+ [(0, 68), (-15, 67), (-9, 67), (-14, 72)],
555+ [(-14, 70), (-20, 62), (-1, 61), (-16, 67)],
556+ [(-24, 56), (-19, 70), (-8, 66), (-8, 53)],
557+ [(-23, 68), (-16, 66), (-14, 66), (-14, 59)],
558+ [(-24, 50), (-22, 65), (0, 59), (-9, 52)],
559+ [(-11, 74), (-20, 63), (2, 59), (-11, 68)],
560+ [(23, -13), (9, -2), (17, -10), (9, -2)],
561+ [(26, -13), (26, -9), (32, -13), (30, -10)],
562+ [(40, -15), (33, -9), (42, -9), (31, -4)],
563+ [(49, -14), (39, -7), (49, -5), (33, -1)],
564+ [(44, 3), (41, -2), (53, 0), (33, 7)],
565+ [(45, 6), (45, 3), (64, 3), (31, 12)],
566+ [(44, 34), (49, 9), (68, 10), (37, 23)],
567+ [(33, 54), (45, 27), (66, 27), (31, 38)],
568+ [(19, 82), (36, 59), (47, 57), (20, 64)],
569+ [(-3, 75), (-6, 66), (-5, 71), (-9, 71)],
570+ [(-1, 23), (-7, 35), (0, 24), (-7, 37)],
571+ [(1, 34), (-7, 42), (-1, 36), (-8, 44)],
572+ [(1, 43), (-8, 45), (-2, 42), (-11, 49)],
573+ [(0, 54), (-5, 48), (-2, 52), (-10, 56)],
574+ [(-2, 55), (-12, 56), (-9, 57), (-12, 59)],
575+ [(0, 61), (-6, 60), (-6, 63), (-8, 63)],
576+ [(1, 64), (-5, 62), (-4, 65), (-9, 67)],
577+ [(0, 68), (-8, 66), (-4, 67), (-6, 68)],
578+ [(-9, 92), (-8, 76), (-7, 82), (-10, 79)],
579+ [(-14, 106), (-5, 85), (-3, 81), (-3, 78)],
580+ [(-13, 97), (-6, 81), (-3, 76), (-8, 74)],
581+ [(-15, 90), (-10, 77), (-7, 72), (-9, 72)],
582+ [(-12, 90), (-7, 81), (-6, 78), (-10, 72)],
583+ [(-18, 88), (-17, 80), (-12, 72), (-18, 75)],
584+ [(-10, 73), (-18, 73), (-14, 68), (-12, 71)],
585+ [(-9, 79), (-4, 74), (-3, 70), (-11, 63)],
586+ [(-14, 86), (-10, 83), (-6, 76), (-5, 70)],
587+ [(-10, 73), (-9, 71), (-5, 66), (-17, 75)],
588+ [(-10, 70), (-9, 67), (-5, 62), (-14, 72)],
589+ [(-10, 69), (-1, 61), (0, 57), (-16, 67)],
590+ [(-5, 66), (-8, 66), (-4, 61), (-8, 53)],
591+ [(-9, 64), (-14, 66), (-9, 60), (-14, 59)],
592+ [(-5, 58), (0, 59), (1, 54), (-9, 52)],
593+ [(2, 59), (2, 59), (2, 58), (-11, 68)],
594+ [(21, -10), (21, -13), (17, -10), (9, -2)],
595+ [(24, -11), (33, -14), (32, -13), (30, -10)],
596+ [(28, -8), (39, -7), (42, -9), (31, -4)],
597+ [(28, -1), (46, -2), (49, -5), (33, -1)],
598+ [(29, 3), (51, 2), (53, 0), (33, 7)],
599+ [(29, 9), (60, 6), (64, 3), (31, 12)],
600+ [(35, 20), (61, 17), (68, 10), (37, 23)],
601+ [(29, 36), (55, 34), (66, 27), (31, 38)],
602+ [(14, 67), (42, 62), (47, 57), (20, 64)],
603+];
604+
605+
606+// ---------------------------------------------------------------------------------
607+// ctxBlockCat 5 (luma 8x8) position maps — spec Table 9-43.
608+//
609+// Moved here from `rusty_h264-decoder/src/mb16.rs` (rip/R6-1) so the ENCODER can share
610+// them. The decoder has decoded x264's High-profile 8x8 streams bit-exact with these
611+// since c1375d1/d137218, so they are validated spec data, not a fresh transcription —
612+// which is the whole reason the encoder work reuses them rather than re-deriving.
613+//
614+// Cat 5 is the odd category in two ways, both of which matter to a writer:
615+// * ctxIdxInc is NOT the scan position (as it is for the 4x4 cats) — 63 positions
616+// fold onto 15 contexts for `significant_coeff_flag` and 9 for
617+// `last_significant_coeff_flag`.
618+// * it carries NO `coded_block_flag`; presence is inferred from
619+// CodedBlockPatternLuma. Emitting one desyncs the stream.
620+// ---------------------------------------------------------------------------------
621+
622+/// `significant_coeff_flag` ctxIdxInc for ctxBlockCat 5, frame-coded (spec Table 9-43).
623+/// Absolute ctxIdx is `402 + SIG8X8[pos]` (encoder) / the decoder's matching base.
624+pub const SIG8X8: [u8; 64] = [
625+ 0, 1, 2, 3, 4, 5, 5, 4, 4, 3, 3, 4, 4, 4, 5, 5, //
626+ 4, 4, 4, 4, 3, 3, 6, 7, 7, 7, 8, 9, 10, 9, 8, 7, //
627+ 7, 6, 11, 12, 13, 11, 6, 7, 8, 9, 14, 10, 9, 8, 6, 11, //
628+ 12, 13, 11, 6, 9, 14, 10, 9, 11, 12, 13, 11, 14, 10, 12, 14,
629+];
630+
631+/// `last_significant_coeff_flag` ctxIdxInc for ctxBlockCat 5 (spec Table 9-43).
632+/// Absolute ctxIdx is `417 + LAST8X8[pos]`.
633+pub const LAST8X8: [u8; 64] = [
634+ 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, //
635+ 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, //
636+ 3, 3, 3, 3, 3, 3, 3, 3, 4, 4, 4, 4, 4, 4, 4, 4, //
637+ 5, 5, 5, 5, 6, 6, 6, 6, 7, 7, 7, 7, 8, 8, 8, 8,
638+];
639+
640+/// ctxIdxOffset bases for ctxBlockCat 5, spec Table 9-34. Named so the encoder's
641+/// residual writer cannot silently disagree with the decoder's reader.
642+pub const CAT5_SIG_BASE: usize = 402;
643+pub const CAT5_LAST_BASE: usize = 417;
644+pub const CAT5_LEVEL_BASE: usize = 426;
vendor/rusty_h264-common/src/cavlc.rsadded+821 -0
@@ -0,0 +1,821 @@
1+//! CAVLC — Context-Adaptive Variable-Length Coding of residual blocks.
2+//!
3+//! This is the entropy coder that actually compresses: a 4×4 block of quantized
4+//! coefficients (in zig-zag scan order) is coded as `coeff_token` (count +
5+//! trailing ones), trailing-one signs, the remaining levels, `total_zeros`, and
6+//! per-coefficient `run_before`. The VLC tables below are the exact H.264 tables
7+//! (matching the reference decoders our output is validated against).
8+//!
9+//! [`encode_residual_block`] and [`decode_residual_block`] are an exact inverse
10+//! pair, parameterized by `nc` (the neighbor-derived context that selects the
11+//! `coeff_token` table) and `max_coeff` (16 for a full 4×4, 15 for an AC block,
12+//! 4 for chroma DC). Neighbor `nc` bookkeeping lives in the macroblock layer.
13+
14+use crate::{BitReader, BitWriter};
15+use crate::bit_reader::OutOfData;
16+
17+/// 4×4 zig-zag scan: scan position → raster index.
18+pub const ZIGZAG_4X4: [usize; 16] = [
19+ 0, 1, 4, 8, 5, 2, 3, 6, 9, 12, 13, 10, 7, 11, 14, 15,
20+];
21+
22+/// Zig-zag scan of a raster 4×4 block (full DC+AC), **unrolled** like openh264's
23+/// `WelsScan4x4DcAc` — constant indices, so no `ZIGZAG_4X4[i]` table read and no
24+/// per-element bounds check (the looped `block[ZIGZAG_4X4[i]]` form forces one).
25+#[inline]
26+pub fn scan_4x4_dcac(d: &[i32; 16]) -> [i32; 16] {
27+ [
28+ d[0], d[1], d[4], d[8], d[5], d[2], d[3], d[6], d[9], d[12], d[13], d[10], d[7], d[11],
29+ d[14], d[15],
30+ ]
31+}
32+
33+/// Zig-zag scan of the 15 AC coefficients (skipping DC), unrolled like openh264's
34+/// `WelsScan4x4Ac` (`= ZIGZAG_4X4[1..]`).
35+#[inline]
36+pub fn scan_4x4_ac(d: &[i32; 16]) -> [i32; 15] {
37+ [
38+ d[1], d[4], d[8], d[5], d[2], d[3], d[6], d[9], d[12], d[13], d[10], d[7], d[11], d[14],
39+ d[15],
40+ ]
41+}
42+
43+/// Inverse of [`scan_4x4_dcac`] (decoder): scatter scan-order coefficients back to
44+/// the raster 4×4 block, unrolled (no `ZIGZAG_4X4[i]` table read / bounds check).
45+#[inline]
46+pub fn un_scan_4x4_dcac(s: &[i32; 16]) -> [i32; 16] {
47+ let mut d = [0i32; 16];
48+ d[0] = s[0];
49+ d[1] = s[1];
50+ d[4] = s[2];
51+ d[8] = s[3];
52+ d[5] = s[4];
53+ d[2] = s[5];
54+ d[3] = s[6];
55+ d[6] = s[7];
56+ d[9] = s[8];
57+ d[12] = s[9];
58+ d[13] = s[10];
59+ d[10] = s[11];
60+ d[7] = s[12];
61+ d[11] = s[13];
62+ d[14] = s[14];
63+ d[15] = s[15];
64+ d
65+}
66+
67+/// Inverse of [`scan_4x4_ac`] (decoder): scatter the 15 AC coefficients into the
68+/// existing block's raster positions (leaving DC `[0]` untouched). `s[0..15]` used.
69+#[inline]
70+pub fn un_scan_4x4_ac_into(s: &[i32], d: &mut [i32; 16]) {
71+ d[1] = s[0];
72+ d[4] = s[1];
73+ d[8] = s[2];
74+ d[5] = s[3];
75+ d[2] = s[4];
76+ d[3] = s[5];
77+ d[6] = s[6];
78+ d[9] = s[7];
79+ d[12] = s[8];
80+ d[13] = s[9];
81+ d[10] = s[10];
82+ d[7] = s[11];
83+ d[11] = s[12];
84+ d[14] = s[13];
85+ d[15] = s[14];
86+}
87+
88+/// `coded_block_pattern` for Intra macroblocks (4:2:0), indexed by `codeNum`
89+/// (the `me(v)` mapping, spec Table 9-4). Maps code number → CBP value.
90+#[rustfmt::skip]
91+const CBP_INTRA: [u8; 48] = [
92+ 47, 31, 15, 0, 23, 27, 29, 30, 7, 11, 13, 14, 39, 43, 45, 46,
93+ 16, 3, 5, 10, 12, 19, 21, 26, 28, 35, 37, 42, 44, 1, 2, 4,
94+ 8, 17, 18, 20, 24, 6, 9, 22, 25, 32, 33, 34, 36, 40, 38, 41,
95+];
96+
97+/// `coded_block_pattern` for Inter macroblocks (4:2:0), indexed by `codeNum`.
98+#[rustfmt::skip]
99+const CBP_INTER: [u8; 48] = [
100+ 0, 16, 1, 2, 4, 8, 32, 3, 5, 10, 12, 15, 47, 7, 11, 13,
101+ 14, 6, 9, 31, 35, 37, 42, 44, 33, 34, 36, 40, 39, 43, 45, 46,
102+ 17, 18, 20, 24, 19, 21, 26, 28, 23, 27, 29, 30, 22, 25, 38, 41,
103+];
104+
105+/// Inverse of a `codeNum → cbp` table: `cbp → codeNum`, for a direct lookup in
106+/// the encoder instead of a 48-entry linear `.position()` scan per macroblock.
107+const fn invert_cbp(table: &[u8; 48]) -> [u8; 48] {
108+ let mut inv = [0u8; 48];
109+ let mut i = 0;
110+ while i < 48 {
111+ inv[table[i] as usize] = i as u8;
112+ i += 1;
113+ }
114+ inv
115+}
116+const INV_CBP_INTRA: [u8; 48] = invert_cbp(&CBP_INTRA);
117+const INV_CBP_INTER: [u8; 48] = invert_cbp(&CBP_INTER);
118+
119+/// Decodes a `coded_block_pattern` (`me(v)`) for an Intra macroblock.
120+pub fn read_cbp_intra(r: &mut BitReader) -> Result<u32, OutOfData> {
121+ let code_num = r.read_ue()? as usize;
122+ Ok(*CBP_INTRA.get(code_num).unwrap_or(&0) as u32)
123+}
124+
125+/// Encodes a `coded_block_pattern` (`me(v)`) for an Intra macroblock.
126+pub fn write_cbp_intra(w: &mut BitWriter, cbp: u32) {
127+ w.write_ue(INV_CBP_INTRA[cbp as usize] as u32);
128+}
129+
130+/// Decodes a `coded_block_pattern` (`me(v)`) for an Inter macroblock.
131+pub fn read_cbp_inter(r: &mut BitReader) -> Result<u32, OutOfData> {
132+ let code_num = r.read_ue()? as usize;
133+ Ok(*CBP_INTER.get(code_num).unwrap_or(&0) as u32)
134+}
135+
136+/// Encodes a `coded_block_pattern` (`me(v)`) for an Inter macroblock.
137+pub fn write_cbp_inter(w: &mut BitWriter, cbp: u32) {
138+ w.write_ue(INV_CBP_INTER[cbp as usize] as u32);
139+}
140+
141+// ---- coeff_token, four nC tables. Index = TotalCoeff*4 + TrailingOnes. ----
142+
143+#[rustfmt::skip]
144+const COEFF_TOKEN_LEN: [[u8; 68]; 4] = [
145+ [
146+ 1,0,0,0,
147+ 6,2,0,0, 8,6,3,0, 9,8,7,5, 10,9,8,6,
148+ 11,10,9,7, 13,11,10,8, 13,13,11,9, 13,13,13,10,
149+ 14,14,13,11, 14,14,14,13, 15,15,14,14, 15,15,15,14,
150+ 16,15,15,15, 16,16,16,15, 16,16,16,16, 16,16,16,16,
151+ ],
152+ [
153+ 2,0,0,0,
154+ 6,2,0,0, 6,5,3,0, 7,6,6,4, 8,6,6,4,
155+ 8,7,7,5, 9,8,8,6, 11,9,9,6, 11,11,11,7,
156+ 12,11,11,9, 12,12,12,11, 12,12,12,11, 13,13,13,12,
157+ 13,13,13,13, 13,14,13,13, 14,14,14,13, 14,14,14,14,
158+ ],
159+ [
160+ 4,0,0,0,
161+ 6,4,0,0, 6,5,4,0, 6,5,5,4, 7,5,5,4,
162+ 7,5,5,4, 7,6,6,4, 7,6,6,4, 8,7,7,5,
163+ 8,8,7,6, 9,8,8,7, 9,9,8,8, 9,9,9,8,
164+ 10,9,9,9, 10,10,10,10, 10,10,10,10, 10,10,10,10,
165+ ],
166+ [
167+ 6,0,0,0,
168+ 6,6,0,0, 6,6,6,0, 6,6,6,6, 6,6,6,6,
169+ 6,6,6,6, 6,6,6,6, 6,6,6,6, 6,6,6,6,
170+ 6,6,6,6, 6,6,6,6, 6,6,6,6, 6,6,6,6,
171+ 6,6,6,6, 6,6,6,6, 6,6,6,6, 6,6,6,6,
172+ ],
173+];
174+
175+#[rustfmt::skip]
176+const COEFF_TOKEN_BITS: [[u8; 68]; 4] = [
177+ [
178+ 1,0,0,0,
179+ 5,1,0,0, 7,4,1,0, 7,6,5,3, 7,6,5,3,
180+ 7,6,5,4, 15,6,5,4, 11,14,5,4, 8,10,13,4,
181+ 15,14,9,4, 11,10,13,12, 15,14,9,12, 11,10,13,8,
182+ 15,1,9,12, 11,14,13,8, 7,10,9,12, 4,6,5,8,
183+ ],
184+ [
185+ 3,0,0,0,
186+ 11,2,0,0, 7,7,3,0, 7,10,9,5, 7,6,5,4,
187+ 4,6,5,6, 7,6,5,8, 15,6,5,4, 11,14,13,4,
188+ 15,10,9,4, 11,14,13,12, 8,10,9,8, 15,14,13,12,
189+ 11,10,9,12, 7,11,6,8, 9,8,10,1, 7,6,5,4,
190+ ],
191+ [
192+ 15,0,0,0,
193+ 15,14,0,0, 11,15,13,0, 8,12,14,12, 15,10,11,11,
194+ 11,8,9,10, 9,14,13,9, 8,10,9,8, 15,14,13,13,
195+ 11,14,10,12, 15,10,13,12, 11,14,9,12, 8,10,13,8,
196+ 13,7,9,12, 9,12,11,10, 5,8,7,6, 1,4,3,2,
197+ ],
198+ [
199+ 3,0,0,0,
200+ 0,1,0,0, 4,5,6,0, 8,9,10,11, 12,13,14,15,
201+ 16,17,18,19, 20,21,22,23, 24,25,26,27, 28,29,30,31,
202+ 32,33,34,35, 36,37,38,39, 40,41,42,43, 44,45,46,47,
203+ 48,49,50,51, 52,53,54,55, 56,57,58,59, 60,61,62,63,
204+ ],
205+];
206+
207+/// chroma DC (2×2) coeff_token, index = TotalCoeff*4 + TrailingOnes.
208+#[rustfmt::skip]
209+const CHROMA_DC_COEFF_TOKEN_LEN: [u8; 20] = [
210+ 2,0,0,0, 6,1,0,0, 6,6,3,0, 6,7,7,6, 6,8,8,7,
211+];
212+#[rustfmt::skip]
213+const CHROMA_DC_COEFF_TOKEN_BITS: [u8; 20] = [
214+ 1,0,0,0, 7,1,0,0, 4,6,1,0, 3,3,2,5, 2,3,2,0,
215+];
216+
217+/// total_zeros, indexed `[TotalCoeff-1][total_zeros]` (TotalCoeff 1..15).
218+#[rustfmt::skip]
219+const TOTAL_ZEROS_LEN: [[u8; 16]; 15] = [
220+ [1,3,3,4,4,5,5,6,6,7,7,8,8,9,9,9],
221+ [3,3,3,3,3,4,4,4,4,5,5,6,6,6,6,0],
222+ [4,3,3,3,4,4,3,3,4,5,5,6,5,6,0,0],
223+ [5,3,4,4,3,3,3,4,3,4,5,5,5,0,0,0],
224+ [4,4,4,3,3,3,3,3,4,5,4,5,0,0,0,0],
225+ [6,5,3,3,3,3,3,3,4,3,6,0,0,0,0,0],
226+ [6,5,3,3,3,2,3,4,3,6,0,0,0,0,0,0],
227+ [6,4,5,3,2,2,3,3,6,0,0,0,0,0,0,0],
228+ [6,6,4,2,2,3,2,5,0,0,0,0,0,0,0,0],
229+ [5,5,3,2,2,2,4,0,0,0,0,0,0,0,0,0],
230+ [4,4,3,3,1,3,0,0,0,0,0,0,0,0,0,0],
231+ [4,4,2,1,3,0,0,0,0,0,0,0,0,0,0,0],
232+ [3,3,1,2,0,0,0,0,0,0,0,0,0,0,0,0],
233+ [2,2,1,0,0,0,0,0,0,0,0,0,0,0,0,0],
234+ [1,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0],
235+];
236+#[rustfmt::skip]
237+const TOTAL_ZEROS_BITS: [[u8; 16]; 15] = [
238+ [1,3,2,3,2,3,2,3,2,3,2,3,2,3,2,1],
239+ [7,6,5,4,3,5,4,3,2,3,2,3,2,1,0,0],
240+ [5,7,6,5,4,3,4,3,2,3,2,1,1,0,0,0],
241+ [3,7,5,4,6,5,4,3,3,2,2,1,0,0,0,0],
242+ [5,4,3,7,6,5,4,3,2,1,1,0,0,0,0,0],
243+ [1,1,7,6,5,4,3,2,1,1,0,0,0,0,0,0],
244+ [1,1,5,4,3,3,2,1,1,0,0,0,0,0,0,0],
245+ [1,1,1,3,3,2,2,1,0,0,0,0,0,0,0,0],
246+ [1,0,1,3,2,1,1,1,0,0,0,0,0,0,0,0],
247+ [1,0,1,3,2,1,1,0,0,0,0,0,0,0,0,0],
248+ [0,1,1,2,1,3,0,0,0,0,0,0,0,0,0,0],
249+ [0,1,1,1,1,0,0,0,0,0,0,0,0,0,0,0],
250+ [0,1,1,1,0,0,0,0,0,0,0,0,0,0,0,0],
251+ [0,1,1,0,0,0,0,0,0,0,0,0,0,0,0,0],
252+ [0,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0],
253+];
254+
255+/// chroma DC total_zeros, indexed `[TotalCoeff-1][total_zeros]` (TotalCoeff 1..3).
256+#[rustfmt::skip]
257+const CHROMA_DC_TOTAL_ZEROS_LEN: [[u8; 4]; 3] = [
258+ [1,2,3,3],
259+ [1,2,2,0],
260+ [1,1,0,0],
261+];
262+#[rustfmt::skip]
263+const CHROMA_DC_TOTAL_ZEROS_BITS: [[u8; 4]; 3] = [
264+ [1,1,1,0],
265+ [1,1,0,0],
266+ [1,0,0,0],
267+];
268+
269+/// run_before, indexed `[min(zerosLeft,7)-1][run_before]`.
270+#[rustfmt::skip]
271+const RUN_LEN: [[u8; 15]; 7] = [
272+ [1,1,0,0,0,0,0,0,0,0,0,0,0,0,0],
273+ [1,2,2,0,0,0,0,0,0,0,0,0,0,0,0],
274+ [2,2,2,2,0,0,0,0,0,0,0,0,0,0,0],
275+ [2,2,2,3,3,0,0,0,0,0,0,0,0,0,0],
276+ [2,2,3,3,3,3,0,0,0,0,0,0,0,0,0],
277+ [2,3,3,3,3,3,3,0,0,0,0,0,0,0,0],
278+ [3,3,3,3,3,3,3,4,5,6,7,8,9,10,11],
279+];
280+#[rustfmt::skip]
281+const RUN_BITS: [[u8; 15]; 7] = [
282+ [1,0,0,0,0,0,0,0,0,0,0,0,0,0,0],
283+ [1,1,0,0,0,0,0,0,0,0,0,0,0,0,0],
284+ [3,2,1,0,0,0,0,0,0,0,0,0,0,0,0],
285+ [3,2,1,1,0,0,0,0,0,0,0,0,0,0,0],
286+ [3,2,3,2,1,0,0,0,0,0,0,0,0,0,0],
287+ [3,0,1,3,2,5,4,0,0,0,0,0,0,0,0],
288+ [7,6,5,4,3,2,1,1,1,1,1,1,1,1,1],
289+];
290+
291+/// Selects the coeff_token VLC table from the context `nc`. `nc == -1` is the
292+/// chroma-DC table (handled separately by the caller).
293+fn coeff_token_table(nc: i32) -> usize {
294+ if nc < 2 {
295+ 0
296+ } else if nc < 4 {
297+ 1
298+ } else if nc < 8 {
299+ 2
300+ } else {
301+ 3
302+ }
303+}
304+
305+/// Writes a `(len, bits)` VLC codeword.
306+fn put(w: &mut BitWriter, len: u8, bits: u8) {
307+ debug_assert!(len > 0, "writing an undefined VLC entry");
308+ w.write_bits(bits as u32, len as u32);
309+}
310+
311+/// Reads a VLC by matching accumulated bits against a length/bits table over
312+/// the given candidate symbol indices. Returns the matched symbol index.
313+/// A flat VLC lookup table. The H.264 VLC tables are prefix-free, so a single
314+/// `peek_bits(width)` + index decodes any codeword in O(1) — replacing the old
315+/// bit-at-a-time scan over every candidate. `entry[peeked]` packs
316+/// `(symbol << 5) | length`; `length == 0` marks "no codeword" (corrupt input).
317+struct Vlc {
318+ width: u32,
319+ entry: Vec<u16>,
320+}
321+
322+impl Vlc {
323+ /// Builds the lookup from a `(len, code)` table. For each codeword of length
324+ /// `l` and value `v`, every `width`-bit peek whose top `l` bits equal `v`
325+ /// (the contiguous range `[v<<(width-l), (v+1)<<(width-l))`) maps to it. Codes
326+ /// are prefix-free, so the ranges never overlap.
327+ fn build(lens: &[u8], bits: &[u8]) -> Vlc {
328+ let width = lens.iter().copied().max().unwrap_or(0) as u32;
329+ let mut entry = vec![0u16; 1usize << width];
330+ for (i, (&l, &v)) in lens.iter().zip(bits.iter()).enumerate() {
331+ if l == 0 {
332+ continue;
333+ }
334+ let base = (v as usize) << (width - l as u32);
335+ let span = 1usize << (width - l as u32);
336+ let packed = ((i as u16) << 5) | l as u16;
337+ for e in &mut entry[base..base + span] {
338+ *e = packed;
339+ }
340+ }
341+ Vlc { width, entry }
342+ }
343+
344+ #[inline]
345+ fn read(&self, r: &mut BitReader) -> Result<usize, OutOfData> {
346+ let packed = self.entry[r.peek_bits(self.width) as usize];
347+ let len = (packed & 0x1F) as u32;
348+ if len == 0 {
349+ return Err(OutOfData); // peeked bits matched no codeword → corrupt
350+ }
351+ r.skip_bits(len)?;
352+ Ok((packed >> 5) as usize)
353+ }
354+}
355+
356+/// The CAVLC VLC lookup tables, built once on first decode (≈240 KB).
357+struct VlcTables {
358+ coeff_token: [Vlc; 4],
359+ chroma_dc_coeff_token: Vlc,
360+ total_zeros: [Vlc; 15],
361+ chroma_dc_total_zeros: [Vlc; 3],
362+ run_before: [Vlc; 7],
363+}
364+
365+fn vlc_tables() -> &'static VlcTables {
366+ use std::sync::OnceLock;
367+ static T: OnceLock<VlcTables> = OnceLock::new();
368+ T.get_or_init(|| VlcTables {
369+ coeff_token: std::array::from_fn(|t| Vlc::build(&COEFF_TOKEN_LEN[t], &COEFF_TOKEN_BITS[t])),
370+ chroma_dc_coeff_token: Vlc::build(&CHROMA_DC_COEFF_TOKEN_LEN, &CHROMA_DC_COEFF_TOKEN_BITS),
371+ total_zeros: std::array::from_fn(|t| Vlc::build(&TOTAL_ZEROS_LEN[t], &TOTAL_ZEROS_BITS[t])),
372+ chroma_dc_total_zeros: std::array::from_fn(|t| {
373+ Vlc::build(&CHROMA_DC_TOTAL_ZEROS_LEN[t], &CHROMA_DC_TOTAL_ZEROS_BITS[t])
374+ }),
375+ run_before: std::array::from_fn(|t| Vlc::build(&RUN_LEN[t], &RUN_BITS[t])),
376+ })
377+}
378+
379+/// Maps a signed level to its base `levelCode` (before the first-level offset).
380+fn level_to_code(level: i32) -> i32 {
381+ if level > 0 {
382+ (level << 1) - 2
383+ } else {
384+ (-level << 1) - 1
385+ }
386+}
387+
388+/// Writes one `level_prefix`/`level_suffix` for `code` at the given suffix
389+/// length, the exact inverse of [`decode_residual_block`]'s level parsing.
390+///
391+/// For small codes the prefix is the unary part and the suffix is `suffix_length`
392+/// bits. Above that, `level_prefix` escapes to 15 with a 12-bit suffix; and for
393+/// codes too large for 12 bits, to the **extended escape** (`level_prefix ≥ 16`,
394+/// suffix `level_prefix − 3` bits), without which large levels — common at very
395+/// low QP — would silently truncate.
396+fn write_level(w: &mut BitWriter, code: i32, suffix_length: u32) {
397+ let code = code as u32;
398+ // Short forms with prefix < 15 — prefix+suffix PACKED into one write (the
399+ // value `(1<<suffixsize)|suffix` in `prefix+1+suffixsize` bits, leading zeros
400+ // implicit). Mirrors openh264's single `CAVLC_BS_WRITE` per level.
401+ if suffix_length == 0 {
402+ if code < 14 {
403+ w.write_bits(1, code + 1);
404+ return;
405+ } else if code < 30 {
406+ w.write_bits((1u32 << 4) | (code - 14), 14 + 1 + 4);
407+ return;
408+ }
409+ } else {
410+ let prefix = code >> suffix_length;
411+ if prefix < 15 {
412+ let suffix = code & ((1 << suffix_length) - 1);
413+ w.write_bits((1u32 << suffix_length) | suffix, prefix + 1 + suffix_length);
414+ return;
415+ }
416+ }
417+ // Prefix ≥ 15. `rem` is the value beyond the prefix-15 base; the decoder's
418+ // `+15` for the suffix_length-0 case makes both bases (30 and 15<<sl) align.
419+ let base = if suffix_length == 0 { 30 } else { 15u32 << suffix_length };
420+ let rem = code - base;
421+ if rem < 4096 {
422+ put_zeros_one(w, 15);
423+ w.write_bits(rem, 12);
424+ return;
425+ }
426+ // Extended escape: grow the prefix until the suffix fits. For prefix `p`,
427+ // the suffix is `p − 3` bits and encodes `rem − (2^(p−3) − 4096)`.
428+ let mut p = 16u32;
429+ while rem > (1u32 << (p - 2)) - 4097 {
430+ p += 1;
431+ }
432+ put_zeros_one(w, p);
433+ w.write_bits(rem - ((1 << (p - 3)) - 4096), p - 3);
434+}
435+
436+/// Writes `n` zero bits followed by a `1` (the unary `level_prefix`).
437+fn put_zeros_one(w: &mut BitWriter, n: u32) {
438+ // `n` zero bits then a `1` is just the value `1` written in `n + 1` bits — one
439+ // write, not `n + 1`. (The level-prefix unary code, emitted for every coeff.)
440+ if n < 32 {
441+ w.write_bits(1, n + 1);
442+ } else {
443+ w.write_bits(0, n - 31);
444+ w.write_bits(1, 32);
445+ }
446+}
447+
448+/// Reads a `level_prefix` (count of leading zeros before a `1`).
449+fn read_level_prefix(r: &mut BitReader) -> Result<u32, OutOfData> {
450+ // Unary prefix = leading zeros before a 1. Count them in the peek window in
451+ // one CLZ when the codeword (lz+1 bits) fits the 24-bit window.
452+ let window = r.peek_bits(24);
453+ let lz = window.leading_zeros() - 8;
454+ if lz < 24 {
455+ r.skip_bits(lz + 1)?;
456+ return Ok(lz);
457+ }
458+ let mut n = 0;
459+ while !r.read_bit()? {
460+ n += 1;
461+ // A conformant 4×4 coefficient never needs a prefix this long; beyond
462+ // this the level computation (`1 << (prefix-3)`) would overflow, so a
463+ // longer run means corrupt input.
464+ if n > 32 {
465+ return Err(OutOfData);
466+ }
467+ }
468+ Ok(n)
469+}
470+
471+/// Encodes a 4×4 residual block (`coeffs` in zig-zag scan order) as CAVLC and
472+/// returns `total_coeff` (the non-zero count), which callers reuse as the block's
473+/// `nnz` — saving a separate counting pass.
474+///
475+/// - `max_coeff`: 16 (full), 15 (AC), or 4 (chroma DC).
476+/// - `nc`: neighbor context; pass `-1` for chroma DC.
477+pub fn encode_residual_block(w: &mut BitWriter, coeffs: &[i32], max_coeff: usize, nc: i32) -> usize {
478+ // MEASUREMENT: scope disabled — at 600k+/200k+ calls its own rdtsc pair
479+ // was >50% of the bucket and inflated every enclosing stage.
480+ // let _g = crate::prof::scope(crate::prof::Stage::EncWrite);
481+ debug_assert!(coeffs.len() >= max_coeff);
482+ debug_assert!(max_coeff <= 16);
483+ let chroma_dc = nc == -1;
484+
485+ // openh264 `CavlcParamCal`: ONE descending pass yields levels[] (high→low),
486+ // run[] (high→low), total_coeff, and total_zeros at once — no positions array,
487+ // no second/third pass. Bit-identical to the per-position derivation. Runs for
488+ // every coded 4×4 block, so the saved passes matter.
489+ let mut levels = [0i32; 16];
490+ let mut run_val = [0usize; 16];
491+ let mut total_coeff = 0usize;
492+ let mut total_zeros = 0usize;
493+ let mut idx = max_coeff as isize - 1;
494+ while idx >= 0 && coeffs[idx as usize] == 0 {
495+ idx -= 1;
496+ }
497+ while idx >= 0 {
498+ levels[total_coeff] = coeffs[idx as usize];
499+ idx -= 1;
500+ let mut count_zero = 0usize;
501+ while idx >= 0 && coeffs[idx as usize] == 0 {
502+ count_zero += 1;
503+ idx -= 1;
504+ }
505+ total_zeros += count_zero;
506+ run_val[total_coeff] = count_zero;
507+ total_coeff += 1;
508+ }
509+ let levels_hi_lo = &levels[..total_coeff];
510+
511+ // Trailing ones: leading ±1 entries of the high→low list, capped at 3.
512+ let mut trailing_ones = 0usize;
513+ for &lv in levels_hi_lo {
514+ if lv.abs() == 1 && trailing_ones < 3 {
515+ trailing_ones += 1;
516+ } else {
517+ break;
518+ }
519+ }
520+
521+ // --- coeff_token + trailing-one signs, PACKED into one write (openh264:
522+ // `n += iTrailingOnes; iValue = (iValue << iTrailingOnes) + uiSign`) ---
523+ let tok_idx = total_coeff * 4 + trailing_ones;
524+ let (ct_len, ct_bits) = if chroma_dc {
525+ (CHROMA_DC_COEFF_TOKEN_LEN[tok_idx], CHROMA_DC_COEFF_TOKEN_BITS[tok_idx])
526+ } else {
527+ let t = coeff_token_table(nc);
528+ (COEFF_TOKEN_LEN[t][tok_idx], COEFF_TOKEN_BITS[t][tok_idx])
529+ };
530+ if total_coeff == 0 {
531+ put(w, ct_len, ct_bits);
532+ return 0;
533+ }
534+ // sign bits for the trailing ones (high→low): 1 = negative.
535+ let mut sign = 0u32;
536+ for &lv in levels_hi_lo.iter().take(trailing_ones) {
537+ sign = (sign << 1) | (lv < 0) as u32;
538+ }
539+ w.write_bits(
540+ ((ct_bits as u32) << trailing_ones) | sign,
541+ ct_len as u32 + trailing_ones as u32,
542+ );
543+
544+ // --- remaining levels (high→low) ---
545+ let mut suffix_length = if total_coeff > 10 && trailing_ones < 3 { 1 } else { 0 };
546+ for (k, &lv) in levels_hi_lo.iter().enumerate().skip(trailing_ones) {
547+ let mut code = level_to_code(lv);
548+ if k == trailing_ones && trailing_ones < 3 {
549+ code -= 2;
550+ }
551+ write_level(w, code, suffix_length);
552+ if suffix_length == 0 {
553+ suffix_length = 1;
554+ }
555+ if lv.abs() > (3 << (suffix_length - 1)) && suffix_length < 6 {
556+ suffix_length += 1;
557+ }
558+ }
559+
560+ // --- total_zeros (computed in the single pass above) ---
561+ if total_coeff < max_coeff {
562+ if chroma_dc {
563+ let row = &CHROMA_DC_TOTAL_ZEROS_LEN[total_coeff - 1];
564+ let brow = &CHROMA_DC_TOTAL_ZEROS_BITS[total_coeff - 1];
565+ put(w, row[total_zeros], brow[total_zeros]);
566+ } else {
567+ put(
568+ w,
569+ TOTAL_ZEROS_LEN[total_coeff - 1][total_zeros],
570+ TOTAL_ZEROS_BITS[total_coeff - 1][total_zeros],
571+ );
572+ }
573+ }
574+
575+ // --- run_before (high→low), skipping once no zeros remain ---
576+ // run_val[] (high→low) came from the single pass above.
577+ let mut zeros_left = total_zeros;
578+ for &run in run_val[..total_coeff].iter().take(total_coeff - 1) {
579+ if zeros_left == 0 {
580+ break;
581+ }
582+ let t = zeros_left.min(7) - 1;
583+ put(w, RUN_LEN[t][run], RUN_BITS[t][run]);
584+ zeros_left -= run;
585+ }
586+ total_coeff
587+}
588+
589+/// Decodes a CAVLC residual block into zig-zag-ordered coefficients. The first
590+/// `max_coeff` entries of the returned fixed array are valid (the rest stay zero);
591+/// returning `[i32; 16]` avoids a per-block heap allocation in the decode loop.
592+pub fn decode_residual_block(
593+ r: &mut BitReader,
594+ max_coeff: usize,
595+ nc: i32,
596+) -> Result<[i32; 16], OutOfData> {
597+ let _g = crate::prof::scope(crate::prof::Stage::Entropy);
598+ let chroma_dc = nc == -1;
599+ let mut out = [0i32; 16];
600+
601+ // --- coeff_token ---
602+ let tabs = vlc_tables();
603+ let _tg = crate::prof::scope(crate::prof::Stage::CavTok);
604+ let (total_coeff, trailing_ones) = if chroma_dc {
605+ let idx = tabs.chroma_dc_coeff_token.read(r)?;
606+ (idx / 4, idx % 4)
607+ } else {
608+ let idx = tabs.coeff_token[coeff_token_table(nc)].read(r)?;
609+ (idx / 4, idx % 4)
610+ };
611+ if total_coeff == 0 {
612+ return Ok(out);
613+ }
614+ // A block cannot hold more coefficients than it has positions. A corrupt
615+ // coeff_token that claims otherwise would index the total_zeros tables and
616+ // the output array out of bounds — reject it.
617+ if total_coeff > max_coeff {
618+ return Err(OutOfData);
619+ }
620+
621+ // --- trailing-one signs + remaining levels, high→low (stack, no alloc) ---
622+ drop(_tg);
623+ let _lg = crate::prof::scope(crate::prof::Stage::CavLvl);
624+ let mut levels_hi_lo = [0i32; 16];
625+ for level in levels_hi_lo.iter_mut().take(trailing_ones) {
626+ *level = if r.read_bit()? { -1 } else { 1 };
627+ }
628+ let mut suffix_length = if total_coeff > 10 && trailing_ones < 3 { 1 } else { 0 };
629+ // `k` indexes the level array and gates the first-non-T1-level offset.
630+ #[allow(clippy::needless_range_loop)]
631+ for k in trailing_ones..total_coeff {
632+ let level_prefix = read_level_prefix(r)?;
633+ let level_suffix_size = if level_prefix == 14 && suffix_length == 0 {
634+ 4
635+ } else if level_prefix >= 15 {
636+ level_prefix - 3
637+ } else {
638+ suffix_length
639+ };
640+ let level_suffix = if level_suffix_size > 0 {
641+ r.read_bits(level_suffix_size)?
642+ } else {
643+ 0
644+ };
645+ let mut level_code = (level_prefix.min(15) << suffix_length) as i32 + level_suffix as i32;
646+ if level_prefix >= 15 && suffix_length == 0 {
647+ level_code += 15;
648+ }
649+ if level_prefix >= 16 {
650+ level_code += (1 << (level_prefix - 3)) - 4096;
651+ }
652+ if k == trailing_ones && trailing_ones < 3 {
653+ level_code += 2;
654+ }
655+ let level = if level_code % 2 == 0 {
656+ (level_code + 2) >> 1
657+ } else {
658+ (-level_code - 1) >> 1
659+ };
660+ // Residual coefficients are 16-bit (spec §8.5; ffmpeg stores int16). A
661+ // value outside that range is non-conformant and would overflow the
662+ // dequant/inverse-transform multiplies — reject the block.
663+ if !(-32768..=32767).contains(&level) {
664+ return Err(OutOfData);
665+ }
666+ levels_hi_lo[k] = level;
667+ if suffix_length == 0 {
668+ suffix_length = 1;
669+ }
670+ if level.abs() > (3 << (suffix_length - 1)) && suffix_length < 6 {
671+ suffix_length += 1;
672+ }
673+ }
674+
675+ // --- total_zeros ---
676+ drop(_lg);
677+ let _rg = crate::prof::scope(crate::prof::Stage::CavRun);
678+ let total_zeros = if total_coeff < max_coeff {
679+ if chroma_dc {
680+ tabs.chroma_dc_total_zeros[total_coeff - 1].read(r)?
681+ } else {
682+ tabs.total_zeros[total_coeff - 1].read(r)?
683+ }
684+ } else {
685+ 0
686+ };
687+
688+ // --- run_before (stack, no alloc) ---
689+ let mut run_val = [0usize; 16];
690+ let mut zeros_left = total_zeros;
691+ for run in run_val.iter_mut().take(total_coeff - 1) {
692+ if zeros_left == 0 {
693+ break;
694+ }
695+ let t = zeros_left.min(7) - 1;
696+ let val = tabs.run_before[t].read(r)?;
697+ *run = val;
698+ // A corrupt run_before may exceed the zeros remaining; reject rather
699+ // than underflow.
700+ zeros_left = zeros_left.checked_sub(val).ok_or(OutOfData)?;
701+ }
702+ if total_coeff >= 1 {
703+ run_val[total_coeff - 1] = zeros_left;
704+ }
705+
706+ // --- reconstruct scan-order coefficients ---
707+ let mut coeff_num: isize = -1;
708+ for i in (0..total_coeff).rev() {
709+ coeff_num += run_val[i] as isize + 1;
710+ // Defensive: with the guards above this stays in 0..max_coeff, but never
711+ // let an attacker-shaped run drive an out-of-bounds write.
712+ let pos = coeff_num as usize;
713+ if pos >= out.len() {
714+ return Err(OutOfData);
715+ }
716+ out[pos] = levels_hi_lo[i];
717+ }
718+ Ok(out)
719+}
720+
721+#[cfg(test)]
722+mod tests {
723+ use super::*;
724+
725+ fn roundtrip(block: &[i32], max_coeff: usize, nc: i32) {
726+ let mut w = BitWriter::new();
727+ encode_residual_block(&mut w, block, max_coeff, nc);
728+ w.align_zero();
729+ let bytes = w.into_bytes();
730+ let mut r = BitReader::new(&bytes);
731+ let decoded = decode_residual_block(&mut r, max_coeff, nc).expect("decode");
732+ assert_eq!(&decoded[..max_coeff], &block[..max_coeff], "nc={nc} max={max_coeff}");
733+ }
734+
735+ #[test]
736+ fn all_zero_block() {
737+ roundtrip(&[0; 16], 16, 0);
738+ roundtrip(&[0; 16], 15, 0);
739+ roundtrip(&[0; 4], 4, -1);
740+ }
741+
742+ #[test]
743+ fn single_dc() {
744+ let mut b = [0i32; 16];
745+ b[0] = 5;
746+ roundtrip(&b, 16, 0);
747+ b[0] = -3;
748+ roundtrip(&b, 16, 0);
749+ }
750+
751+ #[test]
752+ fn trailing_ones_and_levels() {
753+ // DC=3, then some zeros, then ±1 trailing ones at higher frequency.
754+ let b = [3, 0, 1, -1, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0];
755+ roundtrip(&b, 16, 0);
756+ }
757+
758+ #[test]
759+ fn many_coeffs_all_contexts() {
760+ let b = [1, -2, 3, -1, 1, 1, -1, 2, -3, 1, -1, 1, 1, -1, 1, -1];
761+ for nc in [0, 2, 4, 8, 20] {
762+ roundtrip(&b, 16, nc);
763+ }
764+ }
765+
766+ #[test]
767+ fn chroma_dc_blocks() {
768+ roundtrip(&[2, -1, 0, 1], 4, -1);
769+ roundtrip(&[0, 0, 0, -1], 4, -1);
770+ roundtrip(&[1, 1, 1, 1], 4, -1);
771+ }
772+
773+ #[test]
774+ fn large_levels_use_escape() {
775+ let b = [200, -150, 47, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0];
776+ roundtrip(&b, 16, 0);
777+ }
778+
779+ #[test]
780+ fn extreme_levels_use_extended_escape() {
781+ // Levels far beyond the 12-bit suffix range force level_prefix ≥ 16;
782+ // these occur at very low QP and previously truncated. Cover both
783+ // suffix_length==0 (single big DC) and grown-suffix_length (a run of
784+ // large levels) paths, and signs.
785+ roundtrip(&[5000, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], 16, 0);
786+ roundtrip(&[-7000, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], 16, 0);
787+ roundtrip(&[30000, -25000, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], 16, 0);
788+ let big = [9000, -9000, 8000, -8000, 7000, -7000, 6000, -6000, 5000, -5000, 4500,
789+ -4500, 4200, -4200, 4096, -4096];
790+ roundtrip(&big, 16, 0);
791+ // chroma DC and AC blocks with extreme levels too
792+ roundtrip(&[6000, -6000, 5000, -5000], 4, -1);
793+ }
794+
795+ #[test]
796+ fn pseudo_random_blocks() {
797+ // Deterministic LCG; exercise many shapes across contexts and sizes.
798+ let mut state = 0x1234_5678u32;
799+ let mut next = || {
800+ state = state.wrapping_mul(1_664_525).wrapping_add(1_013_904_223);
801+ state
802+ };
803+ for _ in 0..2000 {
804+ let mut b = [0i32; 16];
805+ let density = (next() % 16) as usize;
806+ for slot in b.iter_mut().take(density) {
807+ // small signed values, biased toward ±1
808+ let v = (next() % 7) as i32 - 3;
809+ *slot = v;
810+ }
811+ // shuffle into scan positions
812+ for i in (1..16).rev() {
813+ let j = (next() as usize) % (i + 1);
814+ b.swap(i, j);
815+ }
816+ let max_coeff = if next() % 3 == 0 { 15 } else { 16 };
817+ let nc = [0i32, 2, 4, 8][(next() % 4) as usize];
818+ roundtrip(&b, max_coeff, nc);
819+ }
820+ }
821+}
vendor/rusty_h264-common/src/deblock.rsadded+2881 -0

Diff too large; view file

@@ -0,0 +1,2881 @@
1+//! In-loop deblocking filter (spec §8.7), all-intra case.
2+//!
3+//! Smooths block-edge discontinuities on the reconstructed frame. Because intra
4+//! prediction uses *pre*-deblocking samples, this runs as a post-pass over the
5+//! fully-reconstructed frame: macroblocks in raster order, vertical edges then
6+//! horizontal, filtered in place. For an all-intra picture the boundary
7+//! strength is positional — 4 on macroblock edges, 3 on internal 4×4 edges.
8+
9+/// `α` threshold indexed by `indexA` (= clipped QP), spec Table 8-16.
10+#[rustfmt::skip]
11+const ALPHA: [i32; 52] = [
12+ 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,
13+ 4,4,5,6,7,8,9,10,12,13,15,17,20,22,25,28,
14+ 32,36,40,45,50,56,63,71,80,90,101,113,127,144,162,182,203,226,255,255,
15+];
16+
17+/// `β` threshold indexed by `indexB`.
18+#[rustfmt::skip]
19+const BETA: [i32; 52] = [
20+ 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,
21+ 2,2,2,3,3,3,3,4,4,4,6,6,7,7,8,8,
22+ 9,9,10,10,11,11,12,12,13,13,14,14,15,15,16,16,17,17,18,18,
23+];
24+
25+/// `tc0` indexed by `[indexA][bS-1]` for bS ∈ {1,2,3}.
26+#[rustfmt::skip]
27+const TC0: [[i32; 3]; 52] = [
28+ [0,0,0],[0,0,0],[0,0,0],[0,0,0],[0,0,0],[0,0,0],[0,0,0],[0,0,0],
29+ [0,0,0],[0,0,0],[0,0,0],[0,0,0],[0,0,0],[0,0,0],[0,0,0],[0,0,0],
30+ [0,0,0],[0,0,1],[0,0,1],[0,0,1],[0,0,1],[0,1,1],[0,1,1],[1,1,1],
31+ [1,1,1],[1,1,1],[1,1,1],[1,1,2],[1,1,2],[1,1,2],[1,1,2],[1,2,3],
32+ [1,2,3],[2,2,3],[2,2,4],[2,3,4],[2,3,4],[3,3,5],[3,4,6],[3,4,6],
33+ [4,5,7],[4,5,8],[4,6,9],[5,7,10],[6,8,11],[6,8,13],[7,10,14],[8,11,16],
34+ [9,12,18],[10,13,20],[11,15,23],[13,17,25],
35+];
36+
37+#[inline]
38+fn clip1(v: i32) -> u8 {
39+ v.clamp(0, 255) as u8
40+}
41+
42+#[inline]
43+fn clip3(lo: i32, hi: i32, v: i32) -> i32 {
44+ v.clamp(lo, hi)
45+}
46+
47+/// One sample line crossing an edge: `p3..p0 | q0..q3` (indices 0..3 from the
48+/// edge outward). Reads/writes a plane along `stride`-spaced positions.
49+struct Line {
50+ /// Byte offset of q0 (the first sample on the "right"/"below" side).
51+ base: usize,
52+ /// Step between adjacent samples across the edge (1 horizontally, `stride`
53+ /// vertically).
54+ step: isize,
55+}
56+
57+/// Filters luma samples across one edge line. `bs` is 3 (internal) or 4 (MB edge).
58+#[allow(clippy::too_many_arguments)]
59+fn filter_luma_line(plane: &mut [u8], line: &Line, bs: i32, alpha: i32, beta: i32, tc0: i32) {
60+ let at = |i: isize| -> i32 {
61+ plane[(line.base as isize + i * line.step) as usize] as i32
62+ };
63+ let (p0, p1, p2, p3) = (at(-1), at(-2), at(-3), at(-4));
64+ let (q0, q1, q2, q3) = (at(0), at(1), at(2), at(3));
65+
66+ if (p0 - q0).abs() >= alpha || (p1 - p0).abs() >= beta || (q1 - q0).abs() >= beta {
67+ return;
68+ }
69+ let set = |plane: &mut [u8], i: isize, v: u8| {
70+ plane[(line.base as isize + i * line.step) as usize] = v;
71+ };
72+ let ap = (p2 - p0).abs();
73+ let aq = (q2 - q0).abs();
74+
75+ if bs < 4 {
76+ let tc = tc0 + (ap < beta) as i32 + (aq < beta) as i32;
77+ let delta = clip3(-tc, tc, (((q0 - p0) << 2) + (p1 - q1) + 4) >> 3);
78+ set(plane, -1, clip1(p0 + delta));
79+ set(plane, 0, clip1(q0 - delta));
80+ if ap < beta {
81+ let d = clip3(-tc0, tc0, (p2 + ((p0 + q0 + 1) >> 1) - (p1 << 1)) >> 1);
82+ set(plane, -2, clip1(p1 + d));
83+ }
84+ if aq < beta {
85+ let d = clip3(-tc0, tc0, (q2 + ((p0 + q0 + 1) >> 1) - (q1 << 1)) >> 1);
86+ set(plane, 1, clip1(q1 + d));
87+ }
88+ } else {
89+ let strong = (p0 - q0).abs() < (alpha >> 2) + 2;
90+ if strong && ap < beta {
91+ set(plane, -1, clip1((p2 + 2 * p1 + 2 * p0 + 2 * q0 + q1 + 4) >> 3));
92+ set(plane, -2, clip1((p2 + p1 + p0 + q0 + 2) >> 2));
93+ set(plane, -3, clip1((2 * p3 + 3 * p2 + p1 + p0 + q0 + 4) >> 3));
94+ } else {
95+ set(plane, -1, clip1((2 * p1 + p0 + q1 + 2) >> 2));
96+ }
97+ if strong && aq < beta {
98+ set(plane, 0, clip1((q2 + 2 * q1 + 2 * q0 + 2 * p0 + p1 + 4) >> 3));
99+ set(plane, 1, clip1((q2 + q1 + q0 + p0 + 2) >> 2));
100+ set(plane, 2, clip1((2 * q3 + 3 * q2 + q1 + q0 + p0 + 4) >> 3));
101+ } else {
102+ set(plane, 0, clip1((2 * q1 + q0 + p1 + 2) >> 2));
103+ }
104+ }
105+}
106+
107+/// Filters chroma samples across one edge line (only p0/q0 are modified).
108+fn filter_chroma_line(plane: &mut [u8], line: &Line, bs: i32, alpha: i32, beta: i32, tc0: i32) {
109+ let at = |i: isize| -> i32 {
110+ plane[(line.base as isize + i * line.step) as usize] as i32
111+ };
112+ let (p0, p1) = (at(-1), at(-2));
113+ let (q0, q1) = (at(0), at(1));
114+ if (p0 - q0).abs() >= alpha || (p1 - p0).abs() >= beta || (q1 - q0).abs() >= beta {
115+ return;
116+ }
117+ let set = |plane: &mut [u8], i: isize, v: u8| {
118+ plane[(line.base as isize + i * line.step) as usize] = v;
119+ };
120+ if bs < 4 {
121+ let tc = tc0 + 1;
122+ let delta = clip3(-tc, tc, (((q0 - p0) << 2) + (p1 - q1) + 4) >> 3);
123+ set(plane, -1, clip1(p0 + delta));
124+ set(plane, 0, clip1(q0 - delta));
125+ } else {
126+ set(plane, -1, clip1((2 * p1 + p0 + q1 + 2) >> 2));
127+ set(plane, 0, clip1((2 * q1 + q0 + p1 + 2) >> 2));
128+ }
129+}
130+
131+/// Per-4×4-block macroblock info driving boundary-strength derivation.
132+pub struct BlockInfo<'a> {
133+ /// `true` if the block is **inter**-coded (an intra block is `!inter`). Taking
134+ /// the caller's existing inter mask avoids allocating an inverted intra mask
135+ /// per frame in both the decoder and encoder.
136+ pub inter: &'a [bool],
137+ /// Non-zero coefficient count of the block.
138+ pub nnz: &'a [u8],
139+ /// List-0 block motion vector (quarter-pel); ignored for intra.
140+ pub mv: &'a [(i32, i32)],
141+ /// List-0 reference *picture identity* (a stable per-picture id — PicOrderCnt
142+ /// for the decoder, ref index for the encoder; `i32::MIN` = unused/intra).
143+ /// Boundary strength compares the *set* of reference pictures, so the same
144+ /// picture used via different lists matches (spec §8.7.2.1).
145+ pub ref_id: &'a [i32],
146+ /// List-1 motion + reference identity for B blocks (`ref_id1 = i32::MIN`
147+ /// everywhere for P/I, so the extra slot is a no-op there).
148+ pub mv1: &'a [(i32, i32)],
149+ pub ref_id1: &'a [i32],
150+ /// Block-grid width (`mb_w * 4`).
151+ pub w4: usize,
152+ /// Per-macroblock `transform_size_8x8_flag` (length `mb_w * mb_h`). When set,
153+ /// the macroblock's internal 4×4 luma edges (sample columns/rows 4 and 12)
154+ /// are *not* transform boundaries and must not be filtered (spec §8.7).
155+ pub t8x8: &'a [bool],
156+ /// Boundary strengths already derived by the caller, one entry per macroblock
157+ /// in raster order. Empty = derive them here (the decoder path).
158+ pub bs: &'a [MbBs],
159+ /// OPTIONAL reference→identity maps (Brick: WHYS Part 15 item 2). When
160+ /// non-empty, `ref_id`/`ref_id1` hold RAW per-block reference INDICES
161+ /// (negative = none) and these ≤16-entry tables map index → picture
162+ /// identity (POC). This lets the decoder pass its `ref_idx` grids directly
163+ /// instead of materializing two frame-wide pre-mapped `Vec<i32>` shims
164+ /// (230-460 KB + 57,600 mapped elements per frame). Empty = `ref_id`
165+ /// already carries identities (the encoder path and all older callers).
166+ pub poc0: &'a [i32],
167+ pub poc1: &'a [i32],
168+ /// Per-macroblock derivation CLASS (`MB_KIND_*`), one entry per macroblock in
169+ /// raster order. Empty, or `MB_KIND_UNSET`, means "not classified" and the
170+ /// blind gather+derive runs for that macroblock.
171+ ///
172+ /// SAFETY-BY-DESIGN: an unclassified macroblock costs SPEED, never
173+ /// correctness. That inversion is deliberate — the alternative design, where
174+ /// the producer must hit every macroblock exit point or strengths silently go
175+ /// wrong, is exactly the failure `MbBs::UNSET` exists to guard against.
176+ ///
177+ /// The producer must be CONSERVATIVE. In particular `B_Skip` and
178+ /// `B_Direct_16x16` are NOT `MB_KIND_SKIP`: their motion comes from direct
179+ /// prediction and may differ per 4x4 sub-block, so internal edges can legally
180+ /// reach strength 1. Only classify what is uniform BY SYNTAX.
181+ pub kind: &'a [u8],
182+}
183+
184+/// Not classified — take the blind path. Any value outside `0..=3` behaves this way.
185+pub const MB_KIND_UNSET: u8 = 255;
186+pub const MB_KIND_INTRA: u8 = 0;
187+pub const MB_KIND_SKIP: u8 = 1;
188+pub const MB_KIND_INTER_UNIFORM: u8 = 2;
189+pub const MB_KIND_INTER: u8 = 3;
190+
191+impl MbKind {
192+ /// Decode a producer-supplied class byte. `None` = derive blindly.
193+ #[inline]
194+ pub fn from_u8(v: u8) -> Option<Self> {
195+ match v {
196+ MB_KIND_INTRA => Some(MbKind::Intra),
197+ MB_KIND_SKIP => Some(MbKind::Skip),
198+ MB_KIND_INTER_UNIFORM => Some(MbKind::InterUniform),
199+ MB_KIND_INTER => Some(MbKind::Inter),
200+ _ => None,
201+ }
202+ }
203+}
204+
205+/// One macroblock's boundary strengths: `[edge group][segment]` per direction.
206+///
207+/// 32 bytes, mirroring x264's `uint8_t bs[2][8][4]`. Deriving these during ENCODE
208+/// lets the deblocking pass skip the neighbourhood gather and the derivation.
209+#[derive(Clone, Copy, Default, PartialEq, Eq, Debug)]
210+pub struct MbBs {
211+ /// Vertical edges (block columns 0..4); index 0 is the macroblock edge.
212+ pub v: [[u8; 4]; 4],
213+ /// Horizontal edges (block rows 0..4); index 0 is the macroblock edge.
214+ pub h: [[u8; 4]; 4],
215+}
216+
217+impl MbBs {
218+ /// "Not yet derived". The macroblock loop has several exits (free skip,
219+ /// greedy skip, coded) and every one must store its strengths; missing one
220+ /// leaves zeros, silently disabling deblocking for that macroblock — which is
221+ /// exactly the bug the byte-identical gate caught during bring-up.
222+ pub const UNSET: MbBs = MbBs { v: [[0xFF; 4]; 4], h: [[0xFF; 4]; 4] };
223+}
224+
225+/// Sentinel for an unused reference slot.
226+const NO_REF: i32 = i32::MIN;
227+
228+/// One 4×4 block's deblocking state, gathered into a per-macroblock tile.
229+///
230+/// The frame-wide `inter`/`nnz`/`mv`/`ref_id` arrays are indexed `by * w4 + bx`,
231+/// so deriving boundary strengths straight from them costs ~290 scattered loads
232+/// per macroblock (each block is re-read by up to four edges, and vertical edge
233+/// groups stride by `w4`). Gathering the 24 blocks an MB can touch into this
234+/// contiguous tile once turns all 48 edge decisions into stack/L1 reads. x264
235+/// gets the same effect from its `scan8` cache, which is what lets its
236+/// `deblock_strength` kernel be SIMD at ~15 ns/MB.
237+#[derive(Clone, Copy, Default)]
238+struct Blk {
239+ inter: bool,
240+ /// `nnz != 0` — the count itself never matters, only whether it is non-zero.
241+ nz: bool,
242+ ref_id: i32,
243+ mvx: i32,
244+ mvy: i32,
245+ /// List-1 slot (B slices). `NO_REF` on P/I tiles and on uni-L0 blocks, which
246+ /// keeps every comparison below on its single-list fast path there.
247+ ref1: i32,
248+ mv1x: i32,
249+ mv1y: i32,
250+}
251+
252+impl Blk {
253+ #[inline]
254+ fn load(info: &BlockInfo, i: usize) -> Self {
255+ #[cfg(feature = "profile")]
256+ census::BLK_LOADS.fetch_add(1, std::sync::atomic::Ordering::Relaxed);
257+ let (mvx, mvy) = info.mv[i];
258+ let (ref1, (mv1x, mv1y)) = if info.ref_id1.is_empty() {
259+ (NO_REF, (0, 0))
260+ } else {
261+ (info.rid1(i), info.mv1[i])
262+ };
263+ Blk { inter: info.inter[i], nz: info.nnz[i] != 0, ref_id: info.rid(i), mvx, mvy, ref1, mv1x, mv1y }
264+ }
265+
266+ /// Whether two blocks are identical for flat-inter purposes (both lists —
267+ /// on P tiles the list-1 fields are uniformly `NO_REF`/0, so the extra
268+ /// compares are always-true and the P behaviour is unchanged).
269+ #[inline]
270+ fn same_motion(&self, o: &Blk) -> bool {
271+ self.ref_id == o.ref_id
272+ && self.mvx == o.mvx
273+ && self.mvy == o.mvy
274+ && self.ref1 == o.ref1
275+ && self.mv1x == o.mv1x
276+ && self.mv1y == o.mv1y
277+ }
278+}
279+
280+/// The bS==1 motion test on tile entries — mirrors [`BlockInfo::inter_bs1`]
281+/// exactly (its oracle), including the two-slot B rule, but reads registers
282+/// instead of strided frame arrays. The single-list fast path fires whenever
283+/// neither side carries a List-1 slot: all of P, and B edges between uni-L0
284+/// blocks (equivalent to the general rule at n<=1 — a differing ref covers the
285+/// differing-slot-count case, two unused slots give false).
286+#[inline]
287+fn bs1_tile(p: &Blk, q: &Blk) -> bool {
288+ if (p.ref1 == NO_REF) & (q.ref1 == NO_REF) {
289+ let far = ((p.mvx - q.mvx).abs() >= 4) | ((p.mvy - q.mvy).abs() >= 4);
290+ return (p.ref_id != q.ref_id) | ((p.ref_id != NO_REF) & far);
291+ }
292+ let used = |b: &Blk| {
293+ let mut v = [(0i32, (0i32, 0i32)); 2];
294+ let mut n = 0usize;
295+ if b.ref_id != NO_REF {
296+ v[n] = (b.ref_id, (b.mvx, b.mvy));
297+ n += 1;
298+ }
299+ if b.ref1 != NO_REF {
300+ v[n] = (b.ref1, (b.mv1x, b.mv1y));
301+ n += 1;
302+ }
303+ (v, n)
304+ };
305+ let (pv, pn) = used(p);
306+ let (qv, qn) = used(q);
307+ if pn != qn {
308+ return true;
309+ }
310+ let far = |a: (i32, i32), b: (i32, i32)| (a.0 - b.0).abs() >= 4 || (a.1 - b.1).abs() >= 4;
311+ match pn {
312+ 0 => false,
313+ 1 => pv[0].0 != qv[0].0 || far(pv[0].1, qv[0].1),
314+ _ => {
315+ let direct = !far(pv[0].1, qv[0].1) && !far(pv[1].1, qv[1].1);
316+ let swap = !far(pv[0].1, qv[1].1) && !far(pv[1].1, qv[0].1);
317+ if pv[0].0 == pv[1].0 {
318+ qv[0].0 != pv[0].0 || qv[1].0 != pv[0].0 || !(direct || swap)
319+ } else if pv[0].0 == qv[0].0 && pv[1].0 == qv[1].0 {
320+ !direct
321+ } else if pv[0].0 == qv[1].0 && pv[1].0 == qv[0].0 {
322+ !swap
323+ } else {
324+ true
325+ }
326+ }
327+ }
328+}
329+
330+/// Boundary strength from tile entries (spec §8.7.2.1).
331+/// Branchless for the same reason as [`BlockInfo::bs_branchless`], but now with
332+/// every operand already in a register rather than behind a strided load.
333+#[inline]
334+fn bs_tile(p: &Blk, q: &Blk, mb_edge: bool) -> i32 {
335+ let intra = !(p.inter & q.inter);
336+ let nz = p.nz | q.nz;
337+ let moved = bs1_tile(p, q);
338+ let intra_bs = if mb_edge { 4 } else { 3 };
339+ let non_intra = if nz { 2 } else { moved as i32 };
340+ if intra {
341+ intra_bs
342+ } else {
343+ non_intra
344+ }
345+}
346+
347+/// Boundary strength for an edge where BOTH sides are inter — the only case left
348+/// once the per-macroblock intra fills in [`derive_mb_bs`] have run. It can never
349+/// return 3 or 4, which is precisely why x264's `deblock_strength` kernel is
350+/// branch-light enough to vectorise: the intra strengths are not its job.
351+#[inline]
352+fn bs_inter(p: &Blk, q: &Blk) -> i32 {
353+ let nz = p.nz | q.nz;
354+ let moved = bs1_tile(p, q);
355+ if nz {
356+ 2
357+ } else {
358+ moved as i32
359+ }
360+}
361+
362+/// MB-KIND CENSUS — measurement only, `--features profile`, so the shipped and
363+/// benchmarked binaries carry no counter at all (atomics in a 6.5M-call loop have
364+/// measured ~15% wall inflation elsewhere in this workspace).
365+///
366+/// Exists to size the prize of a KIND-AWARE derivation arithmetically before one
367+/// is built. `derive_mb_kind` already reads nothing for Intra, 9 blocks for Skip
368+/// and 16 nnz bytes for InterUniform, against 24 blocks across 5-7 grids for the
369+/// blind `derive_mb` the decoder currently calls — but that only pays if the
370+/// cheap kinds actually dominate real content. Count first.
371+#[cfg(feature = "profile")]
372+pub mod census {
373+ use std::sync::atomic::{AtomicU64, Ordering};
374+ pub static INTRA: AtomicU64 = AtomicU64::new(0);
375+ pub static SKIP: AtomicU64 = AtomicU64::new(0);
376+ pub static UNIFORM: AtomicU64 = AtomicU64::new(0);
377+ pub static INTER: AtomicU64 = AtomicU64::new(0);
378+ /// Block VISITS made by the predicate walk(s). The timing instruments on this
379+ /// box cannot resolve the fusion (two whole-decode runs disagreed in sign; the
380+ /// anatomy bench's within-arm spread reached 45%), so the bankable evidence is
381+ /// the work actually removed, which no amount of drift can move.
382+ pub static PRED_VISITS: AtomicU64 = AtomicU64::new(0);
383+ /// Every `Blk::load` — the per-block, multi-array gather that Brick 2 exists to
384+ /// avoid. This is the PRIMARY evidence for the brick (codec-measurement §15):
385+ /// one run, drift-immune, and it sizes the win as well as proving it.
386+ pub static BLK_LOADS: AtomicU64 = AtomicU64::new(0);
387+ /// Macroblocks that took the PACKED derivation. Coverage matters: a
388+ /// byte-identical result proves nothing if the path never engaged.
389+ pub static PACKED_MB: AtomicU64 = AtomicU64::new(0);
390+ /// Macroblocks that actually REACH the motion-mask derivation (not intra, not
391+ /// uniform) — the denominator for any kernel prize.
392+ pub static MASKS_CALLS: AtomicU64 = AtomicU64::new(0);
393+ /// ...of those, served by the AVX2 single-list kernel (`l1_used == 0`).
394+ pub static MASKS_KERNEL: AtomicU64 = AtomicU64::new(0);
395+ /// ...of those, forced to the scalar two-list set-match (`l1_used != 0`).
396+ /// THIS is the population a two-list kernel would win, and nothing else.
397+ pub static MASKS_L1: AtomicU64 = AtomicU64::new(0);
398+
399+ pub fn reset() {
400+ for c in [
401+ &INTRA, &SKIP, &UNIFORM, &INTER, &PRED_VISITS, &BLK_LOADS, &PACKED_MB,
402+ &MASKS_CALLS, &MASKS_KERNEL, &MASKS_L1,
403+ ] {
404+ c.store(0, Ordering::Relaxed);
405+ }
406+ }
407+
408+ /// Per-kind gather cost in BLOCK LOADS, from `derive_mb_kind`'s own structure.
409+ /// The projection below is a load-count model, not a timing — it says what is
410+ /// worth measuring, and the measurement still has to happen.
411+ pub fn dump() {
412+ let (i, s, u, n) = (
413+ INTRA.load(Ordering::Relaxed),
414+ SKIP.load(Ordering::Relaxed),
415+ UNIFORM.load(Ordering::Relaxed),
416+ INTER.load(Ordering::Relaxed),
417+ );
418+ let tot = (i + s + u + n).max(1);
419+ eprintln!("--- MB-kind census (deblock bS derivation) — {tot} macroblocks ---");
420+ for (name, n_mb, blocks) in
421+ [("Intra", i, 0u64), ("Skip", s, 9), ("InterUniform", u, 16), ("Inter", n, 24)]
422+ {
423+ eprintln!(
424+ " {name:<13} {n_mb:>10} MB {:>5.1}% kind-aware gather: {blocks:>2} blocks vs 24 blind",
425+ 100.0 * n_mb as f64 / tot as f64
426+ );
427+ }
428+ eprintln!(
429+ " Blk::load GATHER loads: {} ({:.2} per MB)",
430+ BLK_LOADS.load(Ordering::Relaxed),
431+ BLK_LOADS.load(Ordering::Relaxed) as f64 / tot as f64
432+ );
433+ eprintln!(
434+ " predicate-walk block VISITS: {} ({:.2} per MB)",
435+ PRED_VISITS.load(Ordering::Relaxed),
436+ PRED_VISITS.load(Ordering::Relaxed) as f64 / tot as f64
437+ );
438+ eprintln!(
439+ " PACKED-path macroblocks: {}",
440+ PACKED_MB.load(Ordering::Relaxed)
441+ );
442+ let mc = MASKS_CALLS.load(Ordering::Relaxed).max(1);
443+ eprintln!(
444+ " mask derivations: {} (AVX2 kernel {} = {:.1}%, scalar two-list {} = {:.1}%)",
445+ MASKS_CALLS.load(Ordering::Relaxed),
446+ MASKS_KERNEL.load(Ordering::Relaxed),
447+ 100.0 * MASKS_KERNEL.load(Ordering::Relaxed) as f64 / mc as f64,
448+ MASKS_L1.load(Ordering::Relaxed),
449+ 100.0 * MASKS_L1.load(Ordering::Relaxed) as f64 / mc as f64,
450+ );
451+ let blind = 24.0 * tot as f64;
452+ let aware = (0 * i + 9 * s + 16 * u + 24 * n) as f64;
453+ eprintln!(
454+ " => block loads {:.0} -> {:.0} ({:.1}% of the gather removed)",
455+ blind,
456+ aware,
457+ 100.0 * (1.0 - aware / blind)
458+ );
459+ }
460+}
461+
462+/// Derive one macroblock's 32 boundary strengths (2 directions × 4 edge groups ×
463+/// 4 segments), x264-style.
464+///
465+/// The structural point: `mb_type` is a per-MACROBLOCK syntax element, so a
466+/// macroblock is wholly intra or wholly inter and intra-ness is not a per-edge
467+/// property. That turns the two expensive cases into constant fills —
468+/// * intra macroblock → internal edges are the constant 3, its own macroblock
469+/// edges the constant 4;
470+/// * flat inter (skip) macroblock → every internal strength is 0;
471+/// — and leaves [`bs_inter`] for the rest. Pinned by `derive_matches_per_edge`.
472+#[inline]
473+fn derive_mb_bs(
474+ tile: &Tile,
475+ mb_x: usize,
476+ mb_y: usize,
477+ flat_inter: bool,
478+ uniform_motion: bool,
479+ mb_t8: bool,
480+ bs_v: &mut [[i32; 4]; 4],
481+ bs_h: &mut [[i32; 4]; 4],
482+) {
483+ let cur_intra = !tile[1][1].inter;
484+
485+ #[cfg(feature = "profile")]
486+ {
487+ use std::sync::atomic::Ordering::Relaxed;
488+ let c = if cur_intra {
489+ &census::INTRA
490+ } else if flat_inter {
491+ &census::SKIP
492+ } else if uniform_motion {
493+ &census::UNIFORM
494+ } else {
495+ &census::INTER
496+ };
497+ c.fetch_add(1, Relaxed);
498+ }
499+
500+ // ---- macroblock edges: 4 if EITHER side is intra, else an inter compare ----
501+ if mb_x > 0 {
502+ bs_v[0] = if cur_intra || !tile[1][0].inter {
503+ [4; 4]
504+ } else {
505+ std::array::from_fn(|seg| bs_inter(&tile[seg + 1][0], &tile[seg + 1][1]))
506+ };
507+ }
508+ if mb_y > 0 {
509+ bs_h[0] = if cur_intra || !tile[0][1].inter {
510+ [4; 4]
511+ } else {
512+ std::array::from_fn(|seg| bs_inter(&tile[0][seg + 1], &tile[1][seg + 1]))
513+ };
514+ }
515+
516+ // ---- internal edges ----
517+ if flat_inter {
518+ return; // all zero by construction (no coefficients, one shared ref+mv)
519+ }
520+ for be in 1..4usize {
521+ // An 8×8-transform macroblock has no transform boundary at 4×4 edges 1/3.
522+ if mb_t8 && (be == 1 || be == 3) {
523+ continue;
524+ }
525+ if cur_intra {
526+ bs_v[be] = [3; 4];
527+ bs_h[be] = [3; 4];
528+ } else if uniform_motion {
529+ // Coefficients alone; 0 or 2, no motion compare.
530+ bs_v[be] = std::array::from_fn(|seg| {
531+ 2 * (tile[seg + 1][be].nz | tile[seg + 1][be + 1].nz) as i32
532+ });
533+ bs_h[be] = std::array::from_fn(|seg| {
534+ 2 * (tile[be][seg + 1].nz | tile[be + 1][seg + 1].nz) as i32
535+ });
536+ } else {
537+ // Both sides are inside this macroblock, so no neighbour read at all.
538+ bs_v[be] = std::array::from_fn(|seg| bs_inter(&tile[seg + 1][be], &tile[seg + 1][be + 1]));
539+ bs_h[be] = std::array::from_fn(|seg| bs_inter(&tile[be][seg + 1], &tile[be + 1][seg + 1]));
540+ }
541+ }
542+}
543+
544+/// What the encoder already knows about a macroblock the moment it finishes
545+/// coding it. Passing it in turns most macroblocks into constant fills and
546+/// removes the neighbourhood gather that made deriving in the encode loop cost
547+/// MORE than deriving in the deblocking pass (the loop's working set is far more
548+/// contended, so a 24-block gather there evicts live encoder data).
549+#[derive(Clone, Copy, PartialEq, Eq, Debug)]
550+pub enum MbKind {
551+ /// Intra: internal strengths are the constant 3, its own macroblock edges 4.
552+ /// Needs NO block reads at all.
553+ Intra,
554+ /// Skip — no coefficients, one shared reference and motion vector — so every
555+ /// internal strength is 0 and only the two macroblock edges are derived.
556+ Skip,
557+ /// Coded inter with a SINGLE partition (P_L0_16x16 — the fast preset's only
558+ /// inter mode). All 16 blocks share one reference and motion vector, so no
559+ /// internal edge can reach strength 1: internal strengths depend on
560+ /// coefficients alone, and the derivation reads 16 nnz bytes instead of
561+ /// gathering 24 blocks across four grids.
562+ InterUniform,
563+ /// Coded inter, multiple partitions: the full derivation.
564+ Inter,
565+}
566+
567+/// Boundary strengths for a macroblock whose kind the caller already knows.
568+///
569+/// `Intra` reads nothing; `Skip` reads one of its own blocks plus the neighbour
570+/// column/row (9 instead of 24); only `Inter` pays the full gather.
571+/// `derive_mb_kind_into` writes the deblock loop's `i32` arrays directly.
572+pub fn derive_mb_kind_into(
573+ info: &BlockInfo,
574+ mb_x: usize,
575+ mb_y: usize,
576+ kind: MbKind,
577+ bs_v: &mut [[i32; 4]; 4],
578+ bs_h: &mut [[i32; 4]; 4],
579+) {
580+ // Direct i32 writes — no MbBs staging + 32 u8→i32 casts.
581+ *bs_v = [[0; 4]; 4];
582+ *bs_h = [[0; 4]; 4];
583+ let (bx0, by0) = (mb_x * 4, mb_y * 4);
584+ let w4 = info.w4;
585+ match kind {
586+ MbKind::Intra => {
587+ if mb_x > 0 {
588+ bs_v[0] = [4; 4];
589+ }
590+ if mb_y > 0 {
591+ bs_h[0] = [4; 4];
592+ }
593+ for e in 1..4 {
594+ bs_v[e] = [3; 4];
595+ bs_h[e] = [3; 4];
596+ }
597+ }
598+ MbKind::Skip => {
599+ let me = Blk::load(info, by0 * w4 + bx0);
600+ if mb_x > 0 {
601+ bs_v[0] = std::array::from_fn(|seg| {
602+ let p = Blk::load(info, (by0 + seg) * w4 + bx0 - 1);
603+ if p.inter {
604+ bs_inter(&p, &me)
605+ } else {
606+ 4
607+ }
608+ });
609+ }
610+ if mb_y > 0 {
611+ bs_h[0] = std::array::from_fn(|seg| {
612+ let p = Blk::load(info, (by0 - 1) * w4 + bx0 + seg);
613+ if p.inter {
614+ bs_inter(&p, &me)
615+ } else {
616+ 4
617+ }
618+ });
619+ }
620+ }
621+ MbKind::InterUniform => {
622+ for e in 1..4usize {
623+ bs_v[e] = std::array::from_fn(|seg| {
624+ let i = (by0 + seg) * w4 + bx0 + e;
625+ 2 * ((info.nnz[i] != 0) | (info.nnz[i - 1] != 0)) as i32
626+ });
627+ bs_h[e] = std::array::from_fn(|seg| {
628+ let i = (by0 + e) * w4 + bx0 + seg;
629+ 2 * ((info.nnz[i] != 0) | (info.nnz[i - w4] != 0)) as i32
630+ });
631+ }
632+ if mb_x > 0 {
633+ bs_v[0] = std::array::from_fn(|seg| {
634+ let qi = (by0 + seg) * w4 + bx0;
635+ let p = Blk::load(info, qi - 1);
636+ if p.inter {
637+ bs_inter(&p, &Blk::load(info, qi))
638+ } else {
639+ 4
640+ }
641+ });
642+ }
643+ if mb_y > 0 {
644+ bs_h[0] = std::array::from_fn(|seg| {
645+ let qi = by0 * w4 + bx0 + seg;
646+ let p = Blk::load(info, qi - w4);
647+ if p.inter {
648+ bs_inter(&p, &Blk::load(info, qi))
649+ } else {
650+ 4
651+ }
652+ });
653+ }
654+ }
655+ MbKind::Inter => {
656+ let m = derive_mb(info, mb_x, mb_y, false);
657+ for e in 0..4 {
658+ for sg in 0..4 {
659+ bs_v[e][sg] = m.v[e][sg] as i32;
660+ bs_h[e][sg] = m.h[e][sg] as i32;
661+ }
662+ }
663+ }
664+ }
665+}
666+
667+pub fn derive_mb_kind(info: &BlockInfo, mb_x: usize, mb_y: usize, kind: MbKind) -> MbBs {
668+ let (bx0, by0) = (mb_x * 4, mb_y * 4);
669+ let w4 = info.w4;
670+ match kind {
671+ MbKind::Intra => {
672+ let mut m = MbBs::default();
673+ if mb_x > 0 {
674+ m.v[0] = [4; 4];
675+ }
676+ if mb_y > 0 {
677+ m.h[0] = [4; 4];
678+ }
679+ for e in 1..4 {
680+ m.v[e] = [3; 4];
681+ m.h[e] = [3; 4];
682+ }
683+ m
684+ }
685+ MbKind::Skip => {
686+ // Internal strengths stay 0: no coefficients and one shared (ref, mv)
687+ // means no internal edge can reach strength 1 or 2.
688+ let mut m = MbBs::default();
689+ let me = Blk::load(info, by0 * w4 + bx0); // all 16 blocks are identical
690+ if mb_x > 0 {
691+ m.v[0] = std::array::from_fn(|seg| {
692+ let p = Blk::load(info, (by0 + seg) * w4 + bx0 - 1);
693+ if p.inter { bs_inter(&p, &me) as u8 } else { 4 }
694+ });
695+ }
696+ if mb_y > 0 {
697+ m.h[0] = std::array::from_fn(|seg| {
698+ let p = Blk::load(info, (by0 - 1) * w4 + bx0 + seg);
699+ if p.inter { bs_inter(&p, &me) as u8 } else { 4 }
700+ });
701+ }
702+ m
703+ }
704+ MbKind::InterUniform => {
705+ let mut m = MbBs::default();
706+ // Internal edges: uniform motion means only coefficients can raise a
707+ // strength, and then only to 2.
708+ for e in 1..4usize {
709+ m.v[e] = std::array::from_fn(|seg| {
710+ let i = (by0 + seg) * w4 + bx0 + e;
711+ 2 * ((info.nnz[i] != 0) | (info.nnz[i - 1] != 0)) as u8
712+ });
713+ m.h[e] = std::array::from_fn(|seg| {
714+ let i = (by0 + e) * w4 + bx0 + seg;
715+ 2 * ((info.nnz[i] != 0) | (info.nnz[i - w4] != 0)) as u8
716+ });
717+ }
718+ // Macroblock edges still cross into the neighbour, and our own
719+ // coefficients vary per block, so both sides are read per segment.
720+ if mb_x > 0 {
721+ m.v[0] = std::array::from_fn(|seg| {
722+ let qi = (by0 + seg) * w4 + bx0;
723+ let p = Blk::load(info, qi - 1);
724+ if p.inter { bs_inter(&p, &Blk::load(info, qi)) as u8 } else { 4 }
725+ });
726+ }
727+ if mb_y > 0 {
728+ m.h[0] = std::array::from_fn(|seg| {
729+ let qi = by0 * w4 + bx0 + seg;
730+ let p = Blk::load(info, qi - w4);
731+ if p.inter { bs_inter(&p, &Blk::load(info, qi)) as u8 } else { 4 }
732+ });
733+ }
734+ m
735+ }
736+ MbKind::Inter => derive_mb(info, mb_x, mb_y, false),
737+ }
738+}
739+
740+/// Derive one macroblock's boundary strengths from the block grids — the entry
741+/// point for computing them during ENCODE.
742+///
743+/// `info.ref_id` may carry the encoder's raw reference indices (negative for
744+/// intra) rather than the `NO_REF` sentinel: reference identity is only ever
745+/// compared between two INTER blocks, which always hold a valid index.
746+/// PACKED per-macroblock boundary-strength inputs — the x264-shaped layout.
747+///
748+/// Everything one macroblock's derivation needs for its own 16 blocks, contiguous,
749+/// in raster order (`k = row * 4 + col`). This is the layout `deblock_strength_avx2`
750+/// works from, and the reason x264 can vectorise a job we currently do 32 times
751+/// scalar and branchy.
752+///
753+/// Sized by the CEILING PROBE (`examples/bs_layout_ceiling.rs`), which measured, at
754+/// 720p on synthetic-but-representative content:
755+///
756+/// * cache lines touched per macroblock: **16-20 strided vs 2 packed**
757+/// * gather cost (cache-warm): **31.1 ns/MB strided vs 12.5 ns/MB packed** (2.49x)
758+///
759+/// Read that second row carefully, because it REFUTED the original justification for
760+/// this work. The whole derivation costs ~400 ns/MB in context, so eliminating the
761+/// gather buys only ~19 ns/MB — about 5% of the derivation, ~1% of decode. **The
762+/// derivation is COMPUTE-bound, not gather-bound**: ~370 ns/MB is the 32 per-edge
763+/// `bs_inter` evaluations themselves (32 edges x ~20-30 cycles ~= 210-320 ns @ 3 GHz,
764+/// which matches). So this layout does NOT pay for itself as a memory optimisation.
765+/// It exists to make the ARITHMETIC vectorisable — `nnz` collapses to shift-and-or on
766+/// a 16-bit mask, and the motion test becomes i16 subtract/abs/compare across 16
767+/// lanes. That distinction decides whether the SIMD stage is worth building, and it
768+/// is the good case: this codebase's flat SIMD results were all memory-bound kernels,
769+/// its wins (DCT/SATD) were compute-bound.
770+///
771+/// SINGLE-LIST ONLY. B macroblocks carrying a List-1 slot fall back to the blind
772+/// path; the two-list rule in `bs1_tile` is not reproduced here.
773+#[derive(Clone, Copy)]
774+#[repr(C, align(32))]
775+pub struct MbPack {
776+ /// Bit `k` set = block `k` has coefficients. The derivation only ever asks
777+ /// "is this block coded", never for the count.
778+ pub nnz_mask: u16,
779+ /// `mb_type` is a per-MACROBLOCK syntax element, so intra-ness is not per-block.
780+ pub inter: bool,
781+ _pad: u8,
782+ /// Quarter-pel motion, per block, SPLIT into x and y planes.
783+ ///
784+ /// Structure-of-arrays on purpose: interleaved `(x,y)` pairs would force the SIMD
785+ /// twin to OR adjacent lanes together (a pairwise reduction), whereas split planes
786+ /// let the x and y compares live in separate registers and OR whole-register.
787+ /// 16 x i16 is exactly one 256-bit load each.
788+ pub mvx: [i16; 16],
789+ pub mvy: [i16; 16],
790+ /// Bit k set = block k carries a List-1 slot. When this is 0 for a macroblock,
791+ /// every internal edge takes the single-list rule and the AVX2 kernel applies;
792+ /// otherwise the two-list set-matching rule runs scalar for that macroblock.
793+ pub l1_used: u16,
794+ pub mvx1: [i16; 16],
795+ pub mvy1: [i16; 16],
796+ pub ref1: [i32; 16],
797+ /// Reference PICTURE IDENTITY per block (`NO_REF` = intra/unused). Kept i32
798+ /// because the decoder supplies a POC, which must stay comparable across slices
799+ /// whose reference lists differ — a `ref_idx` would compare equal across slices
800+ /// that mean different pictures.
801+ pub ref_id: [i32; 16],
802+}
803+
804+impl BlockInfo<'_> {
805+ /// Block `i`'s List-0 reference identity, applying the optional index map.
806+ #[inline]
807+ fn rid(&self, i: usize) -> i32 {
808+ let r = self.ref_id[i];
809+ if self.poc0.is_empty() {
810+ r
811+ } else if r >= 0 {
812+ self.poc0.get(r as usize).copied().unwrap_or(NO_REF)
813+ } else {
814+ NO_REF
815+ }
816+ }
817+
818+ /// Block `i`'s List-1 reference identity (mapped); `NO_REF` when no List-1.
819+ #[inline]
820+ fn rid1(&self, i: usize) -> i32 {
821+ let r = self.ref_id1[i];
822+ if self.poc1.is_empty() {
823+ r
824+ } else if r >= 0 {
825+ self.poc1.get(r as usize).copied().unwrap_or(NO_REF)
826+ } else {
827+ NO_REF
828+ }
829+ }
830+}
831+
832+impl Default for MbPack {
833+ fn default() -> Self {
834+ Self {
835+ nnz_mask: 0,
836+ inter: false,
837+ _pad: 0,
838+ mvx: [0; 16],
839+ mvy: [0; 16],
840+ l1_used: 0,
841+ mvx1: [0; 16],
842+ mvy1: [0; 16],
843+ ref1: [NO_REF; 16],
844+ ref_id: [NO_REF; 16],
845+ }
846+ }
847+}
848+
849+/// Build the packed records for a whole frame in ONE streaming pass.
850+///
851+/// Each frame-wide array is read once, sequentially and prefetch-friendly, instead of
852+/// being hit 3600 times at scattered per-macroblock offsets. Returns `None` when the
853+/// frame carries List-1 data (B slices), which this layout does not model.
854+pub fn pack_frame(info: &BlockInfo, mb_w: usize, mb_h: usize) -> Option<Vec<MbPack>> {
855+ let mut out = Vec::new();
856+ pack_frame_into(info, mb_w, mb_h, &mut out);
857+ Some(out)
858+}
859+
860+/// [`pack_frame`] into a RECYCLED buffer (Brick: WHYS Part 15 item 1). A fresh
861+/// `Vec<MbPack>` was ~1.1 MB allocated + first-touch-faulted EVERY frame — the
862+/// same per-frame-materialization mechanism the banked GridPool brick removed.
863+/// Each record is built in a local and pushed, so a reused allocation is never
864+/// pre-filled: one write per byte, no defaults pass, no page faults.
865+pub fn pack_frame_into(info: &BlockInfo, mb_w: usize, mb_h: usize, out: &mut Vec<MbPack>) {
866+ let has1 = !info.ref_id1.is_empty();
867+ out.clear();
868+ out.reserve(mb_w * mb_h);
869+ for mb_y in 0..mb_h {
870+ for mb_x in 0..mb_w {
871+ out.push(pack_mb(info, has1, mb_x, mb_y));
872+ }
873+ }
874+}
875+
876+/// One macroblock's packed record — the unit of both `pack_frame_into` and the
877+/// rolling-window precompute pass.
878+#[inline]
879+pub fn pack_mb(info: &BlockInfo, has1: bool, mb_x: usize, mb_y: usize) -> MbPack {
880+ let mut rec = MbPack::default();
881+ let (bx0, by0) = (mb_x * 4, mb_y * 4);
882+ rec.inter = info.inter[by0 * info.w4 + bx0];
883+ for r in 0..4 {
884+ let row = (by0 + r) * info.w4 + bx0;
885+ for c in 0..4 {
886+ let i = row + c;
887+ let k = r * 4 + c;
888+ if info.nnz[i] != 0 {
889+ rec.nnz_mask |= 1 << k;
890+ }
891+ rec.mvx[k] = info.mv[i].0 as i16;
892+ rec.mvy[k] = info.mv[i].1 as i16;
893+ rec.ref_id[k] = info.rid(i);
894+ if has1 {
895+ let r1 = info.rid1(i);
896+ rec.ref1[k] = r1;
897+ rec.mvx1[k] = info.mv1[i].0 as i16;
898+ rec.mvy1[k] = info.mv1[i].1 as i16;
899+ if r1 != NO_REF {
900+ rec.l1_used |= 1 << k;
901+ }
902+ }
903+ }
904+ }
905+ rec
906+}
907+
908+/// FUSED pack+derive over the whole frame, with a TWO-ROW ROLLING WINDOW of
909+/// packed records (WHYS Part 16 root-cause lever, bounded form).
910+///
911+/// The frame-buffer pipeline was: pack ALL 3600 records into a ~1.1 MB Vec,
912+/// then a second interleaved loop re-reads them (plus a per-MB gate ladder) to
913+/// derive strengths. Here each record is DERIVED the moment it is built —
914+/// while it and its left/top neighbours are L1-hot — and only `2 × mb_w`
915+/// records (~50 KB at 720p) ever exist. Output is one `MbBs` (32 B) per
916+/// macroblock, which `filter_frame` consumes over its existing PRECOMPUTED
917+/// path, collapsing the per-MB derivation machinery in the hot loop entirely.
918+///
919+/// Byte-identical by the existing oracle chain: `derive_mb_records` is
920+/// `derive_mb_packed`'s own core (pinned to the tile twin by
921+/// `packed_matches_tile`), and the precomputed consumer path is pinned by the
922+/// encoder's use of it. `flat_inter` loop-skips are subsumed by the stored
923+/// zeros + the consuming loops' all-zero early-outs (documented there).
924+pub fn precompute_bs_frame(info: &BlockInfo, mb_w: usize, mb_h: usize, out: &mut Vec<MbBs>) {
925+ let has1 = !info.ref_id1.is_empty();
926+ out.clear();
927+ out.reserve(mb_w * mb_h);
928+ let mut prev_row: Vec<MbPack> = Vec::with_capacity(mb_w);
929+ let mut cur_row: Vec<MbPack> = Vec::with_capacity(mb_w);
930+ for mb_y in 0..mb_h {
931+ cur_row.clear();
932+ for mb_x in 0..mb_w {
933+ cur_row.push(pack_mb(info, has1, mb_x, mb_y));
934+ let cur = &cur_row[mb_x];
935+ let left = if mb_x > 0 { Some(&cur_row[mb_x - 1]) } else { None };
936+ let top = if mb_y > 0 { Some(&prev_row[mb_x]) } else { None };
937+ let mb_t8 = !info.t8x8.is_empty() && info.t8x8[mb_y * mb_w + mb_x];
938+ let (mut bv, mut bh) = ([[0i32; 4]; 4], [[0i32; 4]; 4]);
939+ derive_mb_records(cur, left, top, mb_t8, &mut bv, &mut bh);
940+ let mut m = MbBs { v: [[0; 4]; 4], h: [[0; 4]; 4] };
941+ for e in 0..4 {
942+ for sg in 0..4 {
943+ m.v[e][sg] = bv[e][sg] as u8;
944+ m.h[e][sg] = bh[e][sg] as u8;
945+ }
946+ }
947+ out.push(m);
948+ }
949+ std::mem::swap(&mut prev_row, &mut cur_row);
950+ }
951+}
952+
953+thread_local! {
954+ /// Recycled `pack_frame` buffer (~1.1 MB at 720p), `Cell` so `filter_frame`
955+ /// can `take`/`set` without holding a borrow across its whole MB loop.
956+ static PACK_SCRATCH: core::cell::Cell<Vec<MbPack>> = const { core::cell::Cell::new(Vec::new()) };
957+}
958+
959+/// THE KERNEL INTERFACE — the whole motion half of the derivation as two bitmasks.
960+///
961+/// `bit k` of the returned pair answers "does block `k` differ in motion from its
962+/// LEFT neighbour block `k-1`" and "...from its ABOVE neighbour block `k-4`", using
963+/// the §8.7.2.1 rule that `bs_inter` applies per edge:
964+///
965+/// ```text
966+/// differs(a,b) = ref[a] != ref[b] || (ref[a] != NO_REF && (|dmvx| >= 4 || |dmvy| >= 4))
967+/// ```
968+///
969+/// Bits at `k % 4 == 0` (left) and `k < 4` (up) are DON'T-CARE: those edges are
970+/// macroblock edges, derived separately against the neighbouring record. That is not
971+/// an accident of convenience — it is what makes the SIMD twin cheap, because the
972+/// lane positions a within-128-bit-lane shift corrupts are exactly those positions.
973+///
974+/// Collapsing the derivation to masks is the point of the packed layout: the 24
975+/// internal edges stop being 24 branchy `bs_inter` calls and become bit tests against
976+/// these masks OR'd with `nnz_mask`, which is the form `deblock_strength_avx2` works in.
977+/// Scalar twin of the uniform-motion test — the oracle, and the path on any CPU
978+/// without AVX2. Short-circuits, which is why the SIMD twin's win concentrates on
979+/// UNIFORM macroblocks (where this walks all 15 comparisons).
980+#[inline]
981+pub fn mb_uniform_scalar(p: &MbPack) -> bool {
982+ p.inter
983+ && (1..16).all(|k| {
984+ p.ref_id[k] == p.ref_id[0]
985+ && p.mvx[k] == p.mvx[0]
986+ && p.mvy[k] == p.mvy[0]
987+ && p.ref1[k] == p.ref1[0]
988+ && p.mvx1[k] == p.mvx1[0]
989+ && p.mvy1[k] == p.mvy1[0]
990+ })
991+}
992+
993+/// Dispatcher: AVX2 when present, scalar otherwise. `p.inter` is a per-macroblock
994+/// flag and is checked here, so the kernel only ever answers the 16-lane question.
995+#[inline]
996+pub fn mb_uniform(p: &MbPack) -> bool {
997+ #[cfg(all(target_arch = "x86_64", feature = "asm"))]
998+ if p.inter {
999+ if let Some(u) =
1000+ rusty_h264_accel::mb_uniform(&p.mvx, &p.mvy, &p.ref_id, &p.mvx1, &p.mvy1, &p.ref1)
1001+ {
1002+ return u;
1003+ }
1004+ }
1005+ mb_uniform_scalar(p)
1006+}
1007+
1008+#[inline]
1009+pub fn bs_motion_masks_scalar(p: &MbPack) -> (u16, u16) {
1010+ let differs = |a: usize, b: usize| -> bool { pk_differs(p, a, p, b) };
1011+ let (mut left, mut up) = (0u16, 0u16);
1012+ for k in 0..16usize {
1013+ if k % 4 != 0 && differs(k, k - 1) {
1014+ left |= 1 << k;
1015+ }
1016+ if k >= 4 && differs(k, k - 4) {
1017+ up |= 1 << k;
1018+ }
1019+ }
1020+ // Don't-care bits are already zero here by construction; the masks are spelled out
1021+ // so the SIMD twin (which must clear them explicitly) is comparable on the FULL u16.
1022+ (left & 0xEEEE, up & 0xFFF0)
1023+}
1024+
1025+/// Dispatcher: the AVX2 twin when the CPU has it, the scalar oracle otherwise.
1026+///
1027+/// The scalar version stays the default on any non-AVX2 CPU and remains the
1028+/// reference the SIMD twin is gated against — it is never deleted.
1029+#[inline]
1030+pub fn bs_motion_masks(p: &MbPack) -> (u16, u16) {
1031+ #[cfg(feature = "profile")]
1032+ {
1033+ use std::sync::atomic::Ordering::Relaxed;
1034+ census::MASKS_CALLS.fetch_add(1, Relaxed);
1035+ if p.l1_used == 0 {
1036+ census::MASKS_KERNEL.fetch_add(1, Relaxed);
1037+ } else {
1038+ census::MASKS_L1.fetch_add(1, Relaxed);
1039+ }
1040+ }
1041+ #[cfg(all(target_arch = "x86_64", feature = "asm"))]
1042+ if p.l1_used == 0 {
1043+ // Single-list fast kernel: all of P and uni-L0 B macroblocks.
1044+ if let Some(m) = rusty_h264_accel::bs_motion_masks(&p.mvx, &p.mvy, &p.ref_id, NO_REF) {
1045+ return m;
1046+ }
1047+ } else {
1048+ // TWO-LIST kernel (WHYS Part 16's named lever): the §8.7.2.1
1049+ // set-matching rule vectorized, so B macroblocks with List-1 slots no
1050+ // longer fall to the scalar per-edge walk. Gated bit-exact against the
1051+ // scalar twin by `bs_motion_masks_two_list_matches_scalar` (accel) and
1052+ // the unmasked runtime oracle (`RS_H264_VERIFY_PACKED=1`).
1053+ if let Some(m) = rusty_h264_accel::bs_motion_masks_two_list(
1054+ &p.mvx, &p.mvy, &p.ref_id, &p.mvx1, &p.mvy1, &p.ref1, NO_REF,
1055+ ) {
1056+ return m;
1057+ }
1058+ }
1059+ bs_motion_masks_scalar(p)
1060+}
1061+
1062+/// The §8.7.2.1 motion test over packed operands — the EXACT twin of `bs1_tile`,
1063+/// including the two-list set-matching rule (which is order-independent: a block pair
1064+/// whose two reference pictures match after a SWAP is not "different motion").
1065+///
1066+/// The single-list fast path fires whenever neither side carries a List-1 slot, which
1067+/// is all of P and most uni-predicted B blocks; only the remainder pays the set match.
1068+#[inline]
1069+fn pk_differs(p: &MbPack, pk: usize, q: &MbPack, qk: usize) -> bool {
1070+ let p_has1 = p.ref1[pk] != NO_REF;
1071+ let q_has1 = q.ref1[qk] != NO_REF;
1072+ if !p_has1 && !q_has1 {
1073+ let far = ((p.mvx[pk] - q.mvx[qk]).abs() >= 4) | ((p.mvy[pk] - q.mvy[qk]).abs() >= 4);
1074+ return (p.ref_id[pk] != q.ref_id[qk]) | ((p.ref_id[pk] != NO_REF) & far);
1075+ }
1076+ // Collect the USED reference slots, exactly as `bs1_tile::used` does.
1077+ let used = |b: &MbPack, k: usize| {
1078+ let mut v = [(0i32, (0i32, 0i32)); 2];
1079+ let mut n = 0usize;
1080+ if b.ref_id[k] != NO_REF {
1081+ v[n] = (b.ref_id[k], (b.mvx[k] as i32, b.mvy[k] as i32));
1082+ n += 1;
1083+ }
1084+ if b.ref1[k] != NO_REF {
1085+ v[n] = (b.ref1[k], (b.mvx1[k] as i32, b.mvy1[k] as i32));
1086+ n += 1;
1087+ }
1088+ (v, n)
1089+ };
1090+ let (pv, pn) = used(p, pk);
1091+ let (qv, qn) = used(q, qk);
1092+ if pn != qn {
1093+ return true;
1094+ }
1095+ let far = |a: (i32, i32), b: (i32, i32)| (a.0 - b.0).abs() >= 4 || (a.1 - b.1).abs() >= 4;
1096+ match pn {
1097+ 0 => false,
1098+ 1 => pv[0].0 != qv[0].0 || far(pv[0].1, qv[0].1),
1099+ _ => {
1100+ let direct = !far(pv[0].1, qv[0].1) && !far(pv[1].1, qv[1].1);
1101+ let swap = !far(pv[0].1, qv[1].1) && !far(pv[1].1, qv[0].1);
1102+ if pv[0].0 == pv[1].0 {
1103+ qv[0].0 != pv[0].0 || qv[1].0 != pv[0].0 || !(direct || swap)
1104+ } else if pv[0].0 == qv[0].0 && pv[1].0 == qv[1].0 {
1105+ !direct
1106+ } else if pv[0].0 == qv[1].0 && pv[1].0 == qv[0].0 {
1107+ !swap
1108+ } else {
1109+ true
1110+ }
1111+ }
1112+ }
1113+}
1114+
1115+#[inline]
1116+fn pk_nz(p: &MbPack, k: usize) -> bool {
1117+ (p.nnz_mask >> k) & 1 != 0
1118+}
1119+
1120+/// `bs_inter` over packed operands — both sides inter, so 3 and 4 are unreachable.
1121+/// Mirrors `bs1_tile`'s single-list fast path exactly.
1122+#[inline]
1123+fn pk_bs_inter(p: &MbPack, pk: usize, q: &MbPack, qk: usize) -> i32 {
1124+ if pk_nz(p, pk) | pk_nz(q, qk) {
1125+ return 2;
1126+ }
1127+ let (pr, qr) = (p.ref_id[pk], q.ref_id[qk]);
1128+ let _ = (pr, qr);
1129+ pk_differs(p, pk, q, qk) as i32
1130+}
1131+
1132+/// Derive one macroblock's strengths from PACKED records — the byte-identical twin of
1133+/// `derive_mb_bs`, pinned against it by `packed_matches_tile`.
1134+pub fn derive_mb_packed(
1135+ packs: &[MbPack],
1136+ mb_w: usize,
1137+ mb_x: usize,
1138+ mb_y: usize,
1139+ mb_t8: bool,
1140+ bs_v: &mut [[i32; 4]; 4],
1141+ bs_h: &mut [[i32; 4]; 4],
1142+) -> bool {
1143+ let cur = &packs[mb_y * mb_w + mb_x];
1144+ let left = if mb_x > 0 { Some(&packs[mb_y * mb_w + mb_x - 1]) } else { None };
1145+ let top = if mb_y > 0 { Some(&packs[(mb_y - 1) * mb_w + mb_x]) } else { None };
1146+ derive_mb_records(cur, left, top, mb_t8, bs_v, bs_h)
1147+}
1148+
1149+/// The record-based core of [`derive_mb_packed`]: derive one macroblock's
1150+/// strengths from ITS OWN record plus the left/top neighbours' — the shape the
1151+/// rolling-window precompute pass ([`precompute_bs_frame`]) needs, where only
1152+/// two rows of records exist at a time.
1153+pub fn derive_mb_records(
1154+ cur: &MbPack,
1155+ left: Option<&MbPack>,
1156+ top: Option<&MbPack>,
1157+ mb_t8: bool,
1158+ bs_v: &mut [[i32; 4]; 4],
1159+ bs_h: &mut [[i32; 4]; 4],
1160+) -> bool {
1161+ let cur_intra = !cur.inter;
1162+
1163+ // Both predicates from the packed record: uniform motion needs no neighbour, and
1164+ // "no coefficients" is `nnz_mask == 0` — a single register test replacing a
1165+ // 16-block walk.
1166+ //
1167+ // REFUTED (WHYS Part 16, z=-2.11 REGRESSION, reverted): deriving uniformity
1168+ // from `bs_motion_masks` to save "the second kernel call". The two calls are
1169+ // ASYMMETRIC: this one is a cheap AVX2 compare-to-block-0 that handles
1170+ // two-list B data in vector code, while the masks kernel falls to the SCALAR
1171+ // set-matching walk whenever `l1_used != 0` — most B inter MBs. The
1172+ // population reaching this function on B frames is uniform-heavy, so the
1173+ // "fusion" replaced their one cheap vector call with an expensive scalar
1174+ // walk. Do not retry without making the masks kernel two-list-capable first.
1175+ let uniform = mb_uniform(cur);
1176+ let flat_inter = uniform && cur.nnz_mask == 0;
1177+
1178+ if let Some(l) = left {
1179+ bs_v[0] = if cur_intra || !l.inter {
1180+ [4; 4]
1181+ } else {
1182+ std::array::from_fn(|seg| pk_bs_inter(l, seg * 4 + 3, cur, seg * 4))
1183+ };
1184+ }
1185+ if let Some(t) = top {
1186+ bs_h[0] = if cur_intra || !t.inter {
1187+ [4; 4]
1188+ } else {
1189+ std::array::from_fn(|seg| pk_bs_inter(t, 12 + seg, cur, seg))
1190+ };
1191+ }
1192+
1193+ if flat_inter {
1194+ return true; // internal strengths are 0 by construction
1195+ }
1196+ // Only the general path consumes these; intra fills constants and uniform motion
1197+ // reads coefficients alone.
1198+ let masks = if cur_intra || uniform { (0, 0) } else { bs_motion_masks(cur) };
1199+ for be in 1..4usize {
1200+ if mb_t8 && (be == 1 || be == 3) {
1201+ continue;
1202+ }
1203+ if cur_intra {
1204+ bs_v[be] = [3; 4];
1205+ bs_h[be] = [3; 4];
1206+ } else if uniform {
1207+ // Coefficients alone; the whole edge group is a shift-and-or on the mask.
1208+ bs_v[be] = std::array::from_fn(|seg| {
1209+ 2 * (pk_nz(cur, seg * 4 + be) | pk_nz(cur, seg * 4 + be - 1)) as i32
1210+ });
1211+ bs_h[be] = std::array::from_fn(|seg| {
1212+ 2 * (pk_nz(cur, be * 4 + seg) | pk_nz(cur, (be - 1) * 4 + seg)) as i32
1213+ });
1214+ } else {
1215+ // The general path, now pure bit tests: coefficients from `nnz_mask`,
1216+ // motion from the precomputed masks. No per-edge branching at all.
1217+ let (left, up) = masks;
1218+ bs_v[be] = std::array::from_fn(|seg| {
1219+ let k = seg * 4 + be;
1220+ if pk_nz(cur, k) | pk_nz(cur, k - 1) {
1221+ 2
1222+ } else {
1223+ ((left >> k) & 1) as i32
1224+ }
1225+ });
1226+ bs_h[be] = std::array::from_fn(|seg| {
1227+ let k = be * 4 + seg;
1228+ if pk_nz(cur, k) | pk_nz(cur, k - 4) {
1229+ 2
1230+ } else {
1231+ ((up >> k) & 1) as i32
1232+ }
1233+ });
1234+ }
1235+ }
1236+ false
1237+}
1238+
1239+/// ONE walk of the macroblock's own 16 blocks yielding BOTH predicates the
1240+/// derivation needs: `(uniform_motion, flat_inter)`.
1241+///
1242+/// They are the same walk, by construction:
1243+/// ```text
1244+/// uniform_motion = b0.inter AND every block { inter AND same_motion(b0) }
1245+/// flat_inter = uniform_motion AND no block carries coefficients
1246+/// ```
1247+/// They used to be two independent 16-block scans — and the `uniform_motion` one
1248+/// ran BEFORE `derive_mb_bs`'s `if flat_inter { return }` early-out, so every Skip
1249+/// macroblock paid a full 16-block × 6-compare motion scan whose result was then
1250+/// discarded. The MB-kind census measures Skip at 36.4% (CAVLC) / 65.0% (main) /
1251+/// 57.8% (high) of macroblocks, so that dead scan ran on most of the corpus.
1252+///
1253+/// Byte-identical to the two-scan form: when the walk breaks early both
1254+/// predicates are false, exactly as both original `.all()` chains would be.
1255+#[inline]
1256+fn scan_uniform_flat(tile: &Tile) -> (bool, bool) {
1257+ let b0 = &tile[1][1];
1258+ if !b0.inter {
1259+ return (false, false); // intra MB — neither predicate applies
1260+ }
1261+ let mut any_nz = false;
1262+ for r in 1..5 {
1263+ for c in 1..5 {
1264+ let b = &tile[r][c];
1265+ #[cfg(feature = "profile")]
1266+ census::PRED_VISITS.fetch_add(1, std::sync::atomic::Ordering::Relaxed);
1267+ if !b.inter || !b.same_motion(b0) {
1268+ return (false, false);
1269+ }
1270+ any_nz |= b.nz;
1271+ }
1272+ }
1273+ (true, !any_nz)
1274+}
1275+
1276+/// The pre-fusion arm, kept verbatim as the measurement baseline AND the oracle.
1277+#[inline]
1278+fn scan_two_pass(tile: &Tile) -> (bool, bool) {
1279+ let b0 = &tile[1][1];
1280+ let flat = b0.inter
1281+ && (1..5).all(|r| {
1282+ (1..5).all(|c| {
1283+ let b = &tile[r][c];
1284+ #[cfg(feature = "profile")]
1285+ census::PRED_VISITS.fetch_add(1, std::sync::atomic::Ordering::Relaxed);
1286+ b.inter && !b.nz && b.same_motion(b0)
1287+ })
1288+ });
1289+ let uniform = b0.inter
1290+ && (1..5).all(|r| {
1291+ (1..5).all(|c| {
1292+ #[cfg(feature = "profile")]
1293+ census::PRED_VISITS.fetch_add(1, std::sync::atomic::Ordering::Relaxed);
1294+ tile[r][c].inter && tile[r][c].same_motion(b0)
1295+ })
1296+ });
1297+ (uniform, flat)
1298+}
1299+
1300+/// MEASUREMENT SWITCH — `RS_H264_BS_TWOPASS=1` restores the two independent
1301+/// scans. Both arms live in ONE binary so a bench can alternate them under one
1302+/// thermal state; separate builds on this box drift ~20% run-to-run, which cannot
1303+/// resolve an effect this size. Read once; the branch predicts perfectly.
1304+static BS_TWOPASS: std::sync::atomic::AtomicU8 = std::sync::atomic::AtomicU8::new(0);
1305+
1306+/// Resolve the arm ONCE — hoist this out of any per-macroblock path.
1307+///
1308+/// It used to be read inside `scan_predicates`, i.e. an atomic load plus a branch
1309+/// on every one of 6.48M macroblocks, present in BOTH arms. That is measurement
1310+/// overhead added in order to take a ~2% measurement, and it is the same mistake
1311+/// this workspace has recorded before (a dedup that replaced cheap work with a
1312+/// dependent load + branch and went backwards). Resolve per frame, pass the bool.
1313+fn bs_twopass() -> bool {
1314+ use std::sync::atomic::Ordering;
1315+ match BS_TWOPASS.load(Ordering::Relaxed) {
1316+ 1 => true,
1317+ 2 => false,
1318+ _ => {
1319+ let on = std::env::var_os("RS_H264_BS_TWOPASS").is_some_and(|v| v != "0");
1320+ BS_TWOPASS.store(if on { 1 } else { 2 }, Ordering::Relaxed);
1321+ on
1322+ }
1323+ }
1324+}
1325+
1326+/// MEASUREMENT SWITCH — `RS_H264_NO_MBKIND=1` ignores producer-supplied classes and
1327+/// forces the blind gather for every macroblock, so the kind-aware brick can be
1328+/// alternated against its own baseline inside ONE binary. Resolved ONCE per frame by
1329+/// the caller and passed down: reading it per macroblock would put an atomic load and
1330+/// a branch in both arms of the very thing being measured (see `bs_twopass`).
1331+static NO_MBKIND: std::sync::atomic::AtomicU8 = std::sync::atomic::AtomicU8::new(0);
1332+
1333+/// CORRECTNESS GATE — `RS_H264_VERIFY_MBKIND=1` derives EVERY kind-classified
1334+/// macroblock BOTH ways and asserts they agree. This is the oracle for the whole
1335+/// brick: a producer that mislabels a macroblock (say, calling a `B_Skip` a `Skip`
1336+/// when direct-derived motion differs per 4x4) changes strengths silently, and the
1337+/// byte-identical corpus gate can only tell you THAT something broke, not where.
1338+/// Run it over the corpus once per producer change; it is far too slow to ship.
1339+fn verify_kind() -> bool {
1340+ use std::sync::atomic::Ordering;
1341+ static V: std::sync::atomic::AtomicU8 = std::sync::atomic::AtomicU8::new(0);
1342+ match V.load(Ordering::Relaxed) {
1343+ 1 => true,
1344+ 2 => false,
1345+ _ => {
1346+ let on = std::env::var_os("RS_H264_VERIFY_MBKIND").is_some_and(|v| v != "0");
1347+ V.store(if on { 1 } else { 2 }, Ordering::Relaxed);
1348+ on
1349+ }
1350+ }
1351+}
1352+
1353+/// Compare kind-derived against blind-derived strengths, looking ONLY at the edges
1354+/// the consuming loops actually read. `derive_mb_kind` fills internal groups 1 and 3
1355+/// even for an 8x8-transform macroblock (whose consumers skip them), so a raw
1356+/// array compare would report a difference that cannot reach a pixel.
1357+#[allow(clippy::too_many_arguments)]
1358+fn verify_kind_matches_blind(
1359+ info: &BlockInfo,
1360+ mb_x: usize,
1361+ mb_y: usize,
1362+ mb_t8: bool,
1363+ kind: MbKind,
1364+ flat_inter: bool,
1365+ bs_v: &[[i32; 4]; 4],
1366+ bs_h: &[[i32; 4]; 4],
1367+) {
1368+ let tile = gather_tile(info, mb_x, mb_y);
1369+ let (u, f) = scan_uniform_flat(&tile);
1370+ let (mut vv, mut vh) = ([[0i32; 4]; 4], [[0i32; 4]; 4]);
1371+ derive_mb_bs(&tile, mb_x, mb_y, f, u, mb_t8, &mut vv, &mut vh);
1372+ assert_eq!(
1373+ flat_inter, f,
1374+ "MB ({mb_x},{mb_y}) kind {kind:?}: flat_inter {flat_inter} but blind derived {f}"
1375+ );
1376+ for be in 0..4usize {
1377+ if be == 0 {
1378+ if mb_x > 0 {
1379+ assert_eq!(bs_v[0], vv[0], "MB ({mb_x},{mb_y}) kind {kind:?}: left MB edge");
1380+ }
1381+ if mb_y > 0 {
1382+ assert_eq!(bs_h[0], vh[0], "MB ({mb_x},{mb_y}) kind {kind:?}: top MB edge");
1383+ }
1384+ continue;
1385+ }
1386+ if flat_inter || (mb_t8 && (be == 1 || be == 3)) {
1387+ continue; // consumers skip these entirely
1388+ }
1389+ assert_eq!(bs_v[be], vv[be], "MB ({mb_x},{mb_y}) kind {kind:?}: v internal edge {be}");
1390+ assert_eq!(bs_h[be], vh[be], "MB ({mb_x},{mb_y}) kind {kind:?}: h internal edge {be}");
1391+ }
1392+}
1393+
1394+/// OPT-IN — `RS_H264_BS_PACKED=1` derives strengths from the packed per-macroblock
1395+/// records instead of the strided gather. Default OFF: the ceiling probe measured the
1396+/// direct memory saving at only ~19 ns/MB of a ~400 ns/MB derivation, so this exists
1397+/// as the ENABLER for a vectorised kernel, not as a memory win in its own right.
1398+/// Resolved once per frame and passed down, never read per macroblock.
1399+/// CORRECTNESS PROBE — `RS_H264_VERIFY_PACKED=1` derives every packed macroblock BOTH
1400+/// ways on real bitstreams and reports the first divergence with its coordinates. The
1401+/// unit oracle passes on a synthetic grid; the corpus does not. This names WHERE.
1402+fn verify_packed() -> bool {
1403+ use std::sync::atomic::Ordering;
1404+ static V: std::sync::atomic::AtomicU8 = std::sync::atomic::AtomicU8::new(0);
1405+ match V.load(Ordering::Relaxed) {
1406+ 1 => true,
1407+ 2 => false,
1408+ _ => {
1409+ let on = std::env::var_os("RS_H264_VERIFY_PACKED").is_some_and(|v| v != "0");
1410+ V.store(if on { 1 } else { 2 }, Ordering::Relaxed);
1411+ on
1412+ }
1413+ }
1414+}
1415+
1416+fn bs_packed_on() -> bool {
1417+ use std::sync::atomic::Ordering;
1418+ static ON: std::sync::atomic::AtomicU8 = std::sync::atomic::AtomicU8::new(0);
1419+ match ON.load(Ordering::Relaxed) {
1420+ 1 => true,
1421+ 2 => false,
1422+ _ => {
1423+ // DEFAULT ON since 2026-08-02. Polarity written as an explicit opt-OUT so
1424+ // it is a decision, not a flag accident: an ABSENT variable means the fast
1425+ // path, and only the literal "0" restores the blind gather.
1426+ //
1427+ // Promoted on three independent interleaved runs (main corpus, 1800 frames
1428+ // 720p, pinned, CPU time, ABBA), each with a null arm in the same session:
1429+ // packed layout alone median +1.7% 8/9, z = 2.33
1430+ // + both AVX2 kernels median +6.7% 11/15, z = 1.81
1431+ // + both AVX2 kernels median +3.3% 12/15, z = 2.32 <- deciding run
1432+ // null arms 1.000 / 1.039 z = -1.13 / 0.38
1433+ // The two full-stack runs pool to 23/30, z = 2.92.
1434+ //
1435+ // Honest shape: single-run medians ranged 1.7-6.7% because this box drifts,
1436+ // so the WIN RATE carries the verdict; the median is the effect-size
1437+ // estimate, not the proof.
1438+ let off = std::env::var_os("RS_H264_BS_PACKED").is_some_and(|v| v == "0");
1439+ ON.store(if off { 2 } else { 1 }, Ordering::Relaxed);
1440+ !off
1441+ }
1442+ }
1443+}
1444+
1445+fn kind_gate_off() -> bool {
1446+ use std::sync::atomic::Ordering;
1447+ match NO_MBKIND.load(Ordering::Relaxed) {
1448+ 1 => true,
1449+ 2 => false,
1450+ _ => {
1451+ let off = std::env::var_os("RS_H264_NO_MBKIND").is_some_and(|v| v != "0");
1452+ NO_MBKIND.store(if off { 1 } else { 2 }, Ordering::Relaxed);
1453+ off
1454+ }
1455+ }
1456+}
1457+
1458+#[inline]
1459+fn scan_predicates(tile: &Tile, two_pass: bool) -> (bool, bool) {
1460+ if two_pass {
1461+ scan_two_pass(tile)
1462+ } else {
1463+ scan_uniform_flat(tile)
1464+ }
1465+}
1466+
1467+pub fn derive_mb(info: &BlockInfo, mb_x: usize, mb_y: usize, mb_t8: bool) -> MbBs {
1468+ let tile = gather_tile(info, mb_x, mb_y);
1469+ let (uniform_motion, flat_inter) = scan_predicates(&tile, bs_twopass());
1470+ let (mut bs_v, mut bs_h) = ([[0i32; 4]; 4], [[0i32; 4]; 4]);
1471+ derive_mb_bs(&tile, mb_x, mb_y, flat_inter, uniform_motion, mb_t8, &mut bs_v, &mut bs_h);
1472+ let pack = |a: [[i32; 4]; 4]| a.map(|e| e.map(|x| x as u8));
1473+ MbBs { v: pack(bs_v), h: pack(bs_h) }
1474+}
1475+
1476+/// The 5×5 neighbourhood an MB's edges can reach: row/col 0 are the top and left
1477+/// neighbour blocks, rows/cols 1..=4 the MB's own 4×4 grid. Entries outside the
1478+/// picture stay `Default` and are never read (the frame-edge groups are skipped).
1479+type Tile = [[Blk; 5]; 5];
1480+
1481+/// Gather the tile for macroblock (`mb_x`, `mb_y`).
1482+fn gather_tile(info: &BlockInfo, mb_x: usize, mb_y: usize) -> Tile {
1483+ let mut t: Tile = Default::default();
1484+ let (bx0, by0) = (mb_x * 4, mb_y * 4);
1485+ // The MB's own blocks: four contiguous runs of four.
1486+ for r in 0..4 {
1487+ let row = (by0 + r) * info.w4 + bx0;
1488+ for c in 0..4 {
1489+ t[r + 1][c + 1] = Blk::load(info, row + c);
1490+ }
1491+ }
1492+ if mb_x > 0 {
1493+ for r in 0..4 {
1494+ t[r + 1][0] = Blk::load(info, (by0 + r) * info.w4 + bx0 - 1);
1495+ }
1496+ }
1497+ if mb_y > 0 {
1498+ let row = (by0 - 1) * info.w4 + bx0;
1499+ for c in 0..4 {
1500+ t[0][c + 1] = Blk::load(info, row + c);
1501+ }
1502+ }
1503+ // `mb_type` is a per-macroblock syntax element, so every 4×4 block of a
1504+ // macroblock shares its intra/inter status. `derive_mb_bs` depends on this to
1505+ // replace per-edge intra tests with per-macroblock constant fills.
1506+ debug_assert!(
1507+ (1..5).all(|r| (1..5).all(|c| t[r][c].inter == t[1][1].inter)),
1508+ "macroblock ({mb_x},{mb_y}) mixes intra and inter 4x4 blocks"
1509+ );
1510+ t
1511+}
1512+
1513+/// Selects the boundary-strength derivation. Default (and shipped path) is the
1514+/// per-MB TILE; `RS_H264_DEBLOCK_BRANCHY=1` restores the original per-edge
1515+/// derivation straight off the frame arrays.
1516+///
1517+/// This exists so both arms live in ONE binary and a benchmark can alternate
1518+/// them under the same thermal state — comparing separate builds on this machine
1519+/// has ~20% run-to-run drift, which cannot resolve the effect being measured.
1520+/// It doubles as the fallback switch. Read once; the branch predicts perfectly.
1521+static BS_MODE: std::sync::atomic::AtomicU8 = std::sync::atomic::AtomicU8::new(0);
1522+
1523+fn branchless_bs() -> bool {
1524+ use std::sync::atomic::Ordering;
1525+ match BS_MODE.load(Ordering::Relaxed) {
1526+ 1 => true,
1527+ 2 => false,
1528+ _ => {
1529+ let branchy = std::env::var_os("RS_H264_DEBLOCK_BRANCHY").is_some_and(|v| v != "0");
1530+ BS_MODE.store(if branchy { 2 } else { 1 }, Ordering::Relaxed);
1531+ !branchy
1532+ }
1533+ }
1534+}
1535+
1536+/// Whether the per-MB tile path is active.
1537+fn deblock_tile() -> bool {
1538+ branchless_bs()
1539+}
1540+
1541+/// DEFAULT OFF. Deriving boundary strengths in the encode loop makes the
1542+/// deblocking stage 1.4-1.7x faster but does NOT reduce total encode time: the
1543+/// block grids were never cold (~90 KB at CIF, L2-resident), so the derivation
1544+/// costs the same in a streaming pass, and the encode loop's contended working
1545+/// set makes it cost MORE there — measured, the loop grew about twice the
1546+/// derivation's own cost. Kept behind this switch with its tests, because the
1547+/// machinery is what a future commit-time derivation (values still in registers,
1548+/// no grid re-read) would build on.
1549+static BS_PRECOMP: std::sync::atomic::AtomicU8 = std::sync::atomic::AtomicU8::new(0);
1550+
1551+/// Whether callers may supply precomputed boundary strengths (the encoder path).
1552+pub fn precomputed_bs_enabled() -> bool {
1553+ BS_PRECOMP.load(std::sync::atomic::Ordering::Relaxed) != 0
1554+}
1555+
1556+/// Toggle the precomputed-strength path so a benchmark can ALTERNATE the two
1557+/// designs inside ONE process.
1558+#[doc(hidden)]
1559+pub fn set_precomputed_bs(on: bool) {
1560+ BS_PRECOMP.store(on as u8, std::sync::atomic::Ordering::Relaxed);
1561+}
1562+
1563+/// Force the deblocking boundary-strength arm at runtime. Exists so a benchmark
1564+/// can ALTERNATE the arms inside one process under one thermal state; comparing
1565+/// separate builds cannot resolve the effect on this machine.
1566+#[doc(hidden)]
1567+pub fn set_branchless_bs(on: bool) {
1568+ BS_MODE.store(if on { 1 } else { 2 }, std::sync::atomic::Ordering::Relaxed);
1569+}
1570+
1571+impl BlockInfo<'_> {
1572+ #[inline]
1573+ fn at(&self, bx: usize, by: usize) -> usize {
1574+ by * self.w4 + bx
1575+ }
1576+
1577+ /// Boundary strength between left/above block `p` and current block `q`
1578+ /// (spec §8.7.2.1). `mb_edge` is true on macroblock boundaries.
1579+ ///
1580+ /// Written branchlessly on purpose. Real content mixes intra/inter, coded and
1581+ /// uncoded blocks, and per-block motion, so the natural short-circuit form
1582+ /// (`if intra … else if nnz … else if motion …`) mispredicts on nearly every
1583+ /// 4×4 edge: the anatomy bench measures the identical code at ~240 ns/MB on
1584+ /// uniform data and ~515 ns/MB once the block state varies, which is the
1585+ /// whole of our gap to x264 here (x264 derives bS with a branchless SIMD
1586+ /// kernel). Evaluating all three candidates costs a few extra loads and beats
1587+ /// paying a ~15-cycle mispredict per edge.
1588+ #[inline]
1589+ fn bs(&self, p: usize, q: usize, mb_edge: bool) -> i32 {
1590+ if branchless_bs() {
1591+ self.bs_branchless(p, q, mb_edge)
1592+ } else {
1593+ self.bs_branchy(p, q, mb_edge)
1594+ }
1595+ }
1596+
1597+ /// The original short-circuit form, kept as the A/B arm and the fallback.
1598+ /// Identical output to [`Self::bs_branchless`] by construction.
1599+ fn bs_branchy(&self, p: usize, q: usize, mb_edge: bool) -> i32 {
1600+ if !self.inter[p] || !self.inter[q] {
1601+ if mb_edge {
1602+ 4
1603+ } else {
1604+ 3
1605+ }
1606+ } else if self.nnz[p] > 0 || self.nnz[q] > 0 {
1607+ 2
1608+ } else if self.inter_bs1(p, q) {
1609+ 1
1610+ } else {
1611+ 0
1612+ }
1613+ }
1614+
1615+ #[inline]
1616+ fn bs_branchless(&self, p: usize, q: usize, mb_edge: bool) -> i32 {
1617+ let intra = !(self.inter[p] & self.inter[q]);
1618+ let nz = (self.nnz[p] | self.nnz[q]) != 0;
1619+ let moved = self.inter_bs1(p, q);
1620+ let intra_bs = if mb_edge { 4 } else { 3 };
1621+ // Priority intra > coefficients > motion, as selects rather than branches.
1622+ let motion_bs = moved as i32; // 1 or 0
1623+ let non_intra = if nz { 2 } else { motion_bs };
1624+ if intra {
1625+ intra_bs
1626+ } else {
1627+ non_intra
1628+ }
1629+ }
1630+
1631+ /// Whether two residual-free inter blocks get boundary strength 1: they use
1632+ /// different reference pictures, a different number of motion vectors, or a
1633+ /// motion vector differs by ≥ 1 full sample (matched by reference picture, so
1634+ /// the same picture in different lists is recognised). Spec §8.7.2.1.
1635+ fn inter_bs1(&self, p: usize, q: usize) -> bool {
1636+ // Single-list fast path (P and I slices — `ref_id1` empty). This is the
1637+ // overwhelmingly common case, and it collapses to two comparisons: the
1638+ // general path below builds a two-slot [(ref, mv); 2] array per side and
1639+ // matches on the slot count, which the anatomy bench showed dominates
1640+ // deblocking. Exactly equivalent here: with one list, `pn`/`qn` are just
1641+ // "is the slot used", so a differing ref_id covers both the
1642+ // different-count and different-picture cases, and two unused slots give
1643+ // pn == qn == 0 => false.
1644+ if self.ref_id1.is_empty() {
1645+ // Branchless (see `bs`): `|`/`&` rather than `||`/`&&` so there is no
1646+ // data-dependent branch here either. The single `is_empty` test above
1647+ // is uniform across a whole frame and predicts perfectly.
1648+ let (rp, rq) = (self.ref_id[p], self.ref_id[q]);
1649+ let (a, b) = (self.mv[p], self.mv[q]);
1650+ let far = ((a.0 - b.0).abs() >= 4) | ((a.1 - b.1).abs() >= 4);
1651+ // Differing refs ⇒ bS 1 (this also covers "one slot used, one not",
1652+ // the general path's differing-count case). Both unused ⇒ 0.
1653+ return (rp != rq) | ((rp != NO_REF) & far);
1654+ }
1655+ // (reference id, motion vector) for each used prediction slot.
1656+ let used = |i: usize| {
1657+ let mut v = [(0i32, (0i32, 0i32)); 2];
1658+ let mut n = 0;
1659+ if self.ref_id[i] != NO_REF {
1660+ v[n] = (self.ref_id[i], self.mv[i]);
1661+ n += 1;
1662+ }
1663+ // `ref_id1` may be empty (P frames have no List-1 — the caller skips
1664+ // building it, since every entry would be NO_REF anyway).
1665+ if !self.ref_id1.is_empty() && self.ref_id1[i] != NO_REF {
1666+ v[n] = (self.ref_id1[i], self.mv1[i]);
1667+ n += 1;
1668+ }
1669+ (v, n)
1670+ };
1671+ let (pv, pn) = used(p);
1672+ let (qv, qn) = used(q);
1673+ if pn != qn {
1674+ return true; // different number of motion vectors
1675+ }
1676+ let far = |a: (i32, i32), b: (i32, i32)| (a.0 - b.0).abs() >= 4 || (a.1 - b.1).abs() >= 4;
1677+ match pn {
1678+ 0 => false,
1679+ 1 => pv[0].0 != qv[0].0 || far(pv[0].1, qv[0].1),
1680+ _ => {
1681+ // Two references each: the picture *sets* must match, and the
1682+ // motion vectors for corresponding pictures must be close. If both
1683+ // slots are the same picture, either pairing is acceptable.
1684+ let direct = !far(pv[0].1, qv[0].1) && !far(pv[1].1, qv[1].1);
1685+ let swap = !far(pv[0].1, qv[1].1) && !far(pv[1].1, qv[0].1);
1686+ if pv[0].0 == pv[1].0 {
1687+ qv[0].0 != pv[0].0 || qv[1].0 != pv[0].0 || !(direct || swap)
1688+ } else if pv[0].0 == qv[0].0 && pv[1].0 == qv[1].0 {
1689+ !direct
1690+ } else if pv[0].0 == qv[1].0 && pv[1].0 == qv[0].0 {
1691+ !swap
1692+ } else {
1693+ true // different picture sets
1694+ }
1695+ }
1696+ }
1697+ }
1698+}
1699+
1700+/// Applies the deblocking filter in place to a fully-reconstructed frame. `qp`
1701+/// is the (constant) luma QP, `qpc` the chroma QP, and `info` supplies the
1702+/// per-block state used to derive boundary strengths (for an all-intra frame
1703+/// this reduces to the fixed 4/3 strengths).
1704+/// Edge thresholds `(α, β, tc0[bS-1])` for a given averaged QP and the slice's
1705+/// filter offsets (spec §8.7.2.2): α/tc0 indexed by `indexA`, β by `indexB`.
1706+#[inline]
1707+fn thresholds(qpav: i32, offset_a: i32, offset_b: i32) -> (i32, i32, [i32; 3]) {
1708+ let ia = (qpav + offset_a).clamp(0, 51) as usize;
1709+ let ib = (qpav + offset_b).clamp(0, 51) as usize;
1710+ (ALPHA[ia], BETA[ib], TC0[ia])
1711+}
1712+
1713+#[allow(clippy::too_many_arguments)]
1714+pub fn filter_frame(
1715+ y: &mut [u8],
1716+ u: &mut [u8],
1717+ v: &mut [u8],
1718+ mb_w: usize,
1719+ mb_h: usize,
1720+ mb_qp: &[u8],
1721+ chroma_qp_offset: i32,
1722+ offset_a: i32,
1723+ offset_b: i32,
1724+ info: &BlockInfo,
1725+) {
1726+ filter_frame_rows(y, u, v, mb_w, mb_h, 0..mb_h, mb_qp, chroma_qp_offset, offset_a, offset_b, info)
1727+}
1728+
1729+/// [`filter_frame`] restricted to macroblock rows `rows` — the row-interleave
1730+/// campaign's unit (docs/row-interleave-plan.md R3): the decoder filters row
1731+/// `r` the moment it finishes decoding, spec raster order preserved exactly.
1732+#[allow(clippy::too_many_arguments)]
1733+pub fn filter_frame_rows(
1734+ y: &mut [u8],
1735+ u: &mut [u8],
1736+ v: &mut [u8],
1737+ mb_w: usize,
1738+ mb_h: usize,
1739+ rows: core::ops::Range<usize>,
1740+ mb_qp: &[u8],
1741+ chroma_qp_offset: i32,
1742+ offset_a: i32,
1743+ offset_b: i32,
1744+ info: &BlockInfo,
1745+) {
1746+ let _g = crate::prof::scope(crate::prof::Stage::Deblock);
1747+ let cw = mb_w * 16;
1748+ let ccw = mb_w * 8;
1749+ // Per-edge QP: deblock strength uses the average of the two adjacent
1750+ // macroblocks' QPy (spec §8.7.2). For an internal edge both sides share the
1751+ // current MB's QP. Chroma averages the two MBs' QPc.
1752+ let qpy = |mx: usize, my: usize| mb_qp[my * mb_w + mx] as i32;
1753+ let qpc = |qpy_val: i32| {
1754+ crate::predict::chroma_qp((qpy_val + chroma_qp_offset).clamp(0, 51) as u8) as i32
1755+ };
1756+ // Arms resolved ONCE per frame, never per macroblock (see `bs_twopass`).
1757+ let two_pass = bs_twopass();
1758+ let kind_off = kind_gate_off();
1759+ let verify_kinds = verify_kind();
1760+ // ONE streaming pass over the frame arrays, not 3600 scattered gathers. `None`
1761+ // when the frame carries List-1 data (B slices), which MbPack does not model —
1762+ // those macroblocks keep the blind path.
1763+ let scratch = PACK_SCRATCH.take();
1764+ let packs: Option<Vec<MbPack>> = if bs_packed_on() && info.bs.is_empty() && deblock_tile() {
1765+ let mut buf = scratch;
1766+ {
1767+ let _pg = crate::prof::scope(crate::prof::Stage::DebPack);
1768+ pack_frame_into(info, mb_w, mb_h, &mut buf);
1769+ }
1770+ Some(buf)
1771+ } else {
1772+ PACK_SCRATCH.set(scratch);
1773+ None
1774+ };
1775+
1776+ for mb_y in rows {
1777+ for mb_x in 0..mb_w {
1778+ // `t8x8` may be empty (no MB uses the 8×8 transform — Baseline); treat
1779+ // an empty grid as all-false so the caller can skip allocating it.
1780+ let mb_t8 = !info.t8x8.is_empty() && info.t8x8[mb_y * mb_w + mb_x];
1781+ // A "flat inter MB" — every 4x4 inter, zero nnz, one (ref, mv) pair (e.g.
1782+ // any skip MB) — has bs = 0 on ALL its internal edges by §8.7.2.1 (no
1783+ // coefficients, same reference, identical motion), so the six internal
1784+ // edge groups can be skipped wholesale. Byte-identical control flow.
1785+ // Gather the MB's 4×4 block state once (see `Blk`). Every boundary
1786+ // strength below then reads the tile instead of the strided frame
1787+ // arrays. Only valid for a single reference list; B slices keep the
1788+ // original per-edge path untouched.
1789+ // `deblock_tile()` selects the arm so a bench can alternate the whole
1790+ // brick (tile vs the original per-edge derivation) in one process.
1791+ // Precomputed strengths short-circuit the gather AND the derivation;
1792+ // flat_inter and the t8x8 skips are already baked into the stored
1793+ // zeros, which the all-zero early-out below handles identically.
1794+ let _dg = crate::prof::scope(crate::prof::Stage::DebDerive);
1795+ let precomputed = !info.bs.is_empty();
1796+ // H-33: the tile arm now carries the two-list B rule (`bs1_tile`), so
1797+ // real-world B frames no longer fall back to the strided per-edge path.
1798+ let use_tile = !precomputed && deblock_tile();
1799+ let have_bs = precomputed || use_tile;
1800+
1801+ // KIND-AWARE FAST PATH. When the producer has classified this
1802+ // macroblock, its strengths follow from syntax and the 24-block
1803+ // neighbourhood gather is not needed at all: Intra reads NOTHING, Skip
1804+ // reads 9 blocks, InterUniform reads 16 nnz bytes. `Inter` and UNSET
1805+ // fall through to the blind path below, so an unclassified macroblock
1806+ // costs speed and never correctness.
1807+ //
1808+ // The gather is skipped by CONSTRUCTION here rather than by an early-out
1809+ // inside it — building the 5x5 `Tile` at all is an 800-byte
1810+ // default-initialisation before 24 of its 25 entries are overwritten.
1811+ let fast_kind = if use_tile && !kind_off {
1812+ match info.kind.get(mb_y * mb_w + mb_x).copied().and_then(MbKind::from_u8) {
1813+ Some(k) if k != MbKind::Inter => Some(k),
1814+ _ => None,
1815+ }
1816+ } else {
1817+ None
1818+ };
1819+
1820+ let blind_tile = use_tile && fast_kind.is_none() && packs.is_none();
1821+ // Declared before the predicate chain: the packed derivation produces
1822+ // `flat_inter` and the strengths in ONE traversal, so it cannot be split
1823+ // across the two chains the way the tile path is.
1824+ let mut bs_v = [[0i32; 4]; 4];
1825+ let mut bs_h = [[0i32; 4]; 4];
1826+ let packed_mb = packs.as_ref().filter(|_| use_tile && fast_kind.is_none());
1827+ // MATERIALISE THE TILE ONLY ON THE BLIND PATH. Writing
1828+ // `else { Default::default() }` here cost an 800-byte zero-init of the
1829+ // 5x5 `Tile` on every CLASSIFIED macroblock — i.e. this brick removed a
1830+ // gather and added ~4 GB of memset, and measured 1.2-17.0% SLOWER in
1831+ // 4/4 pairs. `Option` keeps the fast path free of it entirely.
1832+ let tile = if blind_tile { Some(gather_tile(info, mb_x, mb_y)) } else { None };
1833+
1834+ // ONE walk yields both predicates — see `scan_uniform_flat`. The
1835+ // non-tile arm has no `uniform_motion` consumer (it derives per-edge
1836+ // off the frame arrays), so it keeps returning `flat_inter` alone.
1837+ let mut uniform_motion = false;
1838+ let flat_inter = if precomputed {
1839+ false // the stored zeros already encode it
1840+ } else if let Some(k) = fast_kind {
1841+ match k {
1842+ // No coefficients and one shared (ref, mv): every internal
1843+ // strength is 0 by construction.
1844+ MbKind::Skip => true,
1845+ // CAUGHT BY THE ORACLE: a single-partition inter macroblock
1846+ // with NO coefficients is flat too — uniform motion means the
1847+ // blind predicate reduces to exactly "no block has nnz".
1848+ // Hardcoding `false` here was pixel-identical (the strengths
1849+ // are all 0 either way) but made the consuming loops walk the
1850+ // internal edge groups instead of skipping them, throwing away
1851+ // part of the win. 16 contiguous nnz bytes — the same data
1852+ // `derive_mb_kind` already reads for this class.
1853+ MbKind::InterUniform => {
1854+ let (bx0, by0) = (mb_x * 4, mb_y * 4);
1855+ (0..4).all(|r| {
1856+ (0..4).all(|c| info.nnz[(by0 + r) * info.w4 + bx0 + c] == 0)
1857+ })
1858+ }
1859+ _ => false,
1860+ }
1861+ } else if let Some(pk) = packed_mb {
1862+ #[cfg(feature = "profile")]
1863+ census::PACKED_MB.fetch_add(1, std::sync::atomic::Ordering::Relaxed);
1864+ let pflat = derive_mb_packed(pk, mb_w, mb_x, mb_y, mb_t8, &mut bs_v, &mut bs_h);
1865+ if verify_packed() {
1866+ // UNMASKED: all 32 strengths, not just the ones the consuming
1867+ // loops read. A masked oracle can pass while the corpus diverges.
1868+ let t = gather_tile(info, mb_x, mb_y);
1869+ let (u, f) = scan_uniform_flat(&t);
1870+ let (mut tv, mut th) = ([[0i32; 4]; 4], [[0i32; 4]; 4]);
1871+ derive_mb_bs(&t, mb_x, mb_y, f, u, mb_t8, &mut tv, &mut th);
1872+ assert_eq!(pflat, f, "MB ({mb_x},{mb_y}) t8={mb_t8}: flat_inter");
1873+ assert_eq!(bs_v, tv, "MB ({mb_x},{mb_y}) t8={mb_t8} flat={f}: bs_v");
1874+ assert_eq!(bs_h, th, "MB ({mb_x},{mb_y}) t8={mb_t8} flat={f}: bs_h");
1875+ }
1876+ pflat
1877+ } else if blind_tile {
1878+ let (u, f) = scan_predicates(tile.as_ref().unwrap(), two_pass);
1879+ uniform_motion = u;
1880+ f
1881+ } else {
1882+ let b0 = info.at(mb_x * 4, mb_y * 4);
1883+ let mut ok = info.inter[b0];
1884+ if ok {
1885+ let (r0, m0) = (info.ref_id[b0], info.mv[b0]);
1886+ let has1 = !info.ref_id1.is_empty();
1887+ let (r10, m10) = if has1 { (info.ref_id1[b0], info.mv1[b0]) } else { (NO_REF, (0, 0)) };
1888+ 'scan: for by in 0..4 {
1889+ for bx in 0..4 {
1890+ let i = info.at(mb_x * 4 + bx, mb_y * 4 + by);
1891+ if !info.inter[i]
1892+ || info.nnz[i] != 0
1893+ || info.ref_id[i] != r0
1894+ || info.mv[i] != m0
1895+ || (has1 && (info.ref_id1[i] != r10 || info.mv1[i] != m10))
1896+ {
1897+ ok = false;
1898+ break 'scan;
1899+ }
1900+ }
1901+ }
1902+ }
1903+ ok
1904+ };
1905+ // ---- boundary strengths for the whole macroblock, derived ONCE ----
1906+ // The chroma edge groups are CO-LOCATED with luma edges 0 and 2 and
1907+ // derive identical strengths (pinned by `chroma_bs_matches_luma`), so
1908+ // deriving them in the chroma loops recomputed 16 of the 48 per-MB
1909+ // strengths. Guards mirror the consuming loops exactly, so nothing is
1910+ // derived that was not derived before; edges left at zero are exactly
1911+ // the edges those loops skip.
1912+ if packed_mb.is_some() {
1913+ // Already written by `derive_mb_packed` above: unlike the tile path,
1914+ // the packed derivation produces `flat_inter` AND the strengths in one
1915+ // traversal, so it cannot be split across the two chains.
1916+ } else if precomputed {
1917+ let m = &info.bs[mb_y * mb_w + mb_x];
1918+ for e in 0..4 {
1919+ for sg in 0..4 {
1920+ bs_v[e][sg] = m.v[e][sg] as i32;
1921+ bs_h[e][sg] = m.h[e][sg] as i32;
1922+ }
1923+ }
1924+ } else if let Some(k) = fast_kind {
1925+ // Write i32 strengths straight into the consuming arrays. Going via
1926+ // `derive_mb_kind`'s packed `MbBs` cost 32 u8->i32 stores per
1927+ // classified macroblock that the blind path never pays — pure
1928+ // addition on the path that is supposed to be cheaper.
1929+ derive_mb_kind_into(info, mb_x, mb_y, k, &mut bs_v, &mut bs_h);
1930+ if verify_kinds {
1931+ verify_kind_matches_blind(
1932+ info, mb_x, mb_y, mb_t8, k, flat_inter, &bs_v, &bs_h,
1933+ );
1934+ }
1935+ } else if blind_tile {
1936+ derive_mb_bs(
1937+ tile.as_ref().unwrap(),
1938+ mb_x,
1939+ mb_y,
1940+ flat_inter,
1941+ uniform_motion,
1942+ mb_t8,
1943+ &mut bs_v,
1944+ &mut bs_h,
1945+ );
1946+ }
1947+ drop(_dg);
1948+ // ---- luma vertical edges (block columns 0..4) ----
1949+ for be in 0..4usize {
1950+ if be == 0 && mb_x == 0 {
1951+ continue;
1952+ }
1953+ if flat_inter && be != 0 {
1954+ continue; // internal bs all 0 (flat inter MB)
1955+ }
1956+ // 8×8-transform MBs: internal 4×4 edges (be 1, 3) aren't filtered.
1957+ if mb_t8 && (be == 1 || be == 3) {
1958+ continue;
1959+ }
1960+ let mb_edge = be == 0;
1961+ let mut bs4 = [0i32; 4];
1962+ if have_bs {
1963+ bs4 = bs_v[be];
1964+ } else {
1965+ let abx = mb_x * 4 + be;
1966+ for (seg, b) in bs4.iter_mut().enumerate() {
1967+ let aby = mb_y * 4 + seg;
1968+ *b = info.bs(info.at(abx - 1, aby), info.at(abx, aby), mb_edge);
1969+ }
1970+ }
1971+ if bs4.iter().all(|&b| b == 0) {
1972+ continue;
1973+ }
1974+ // Thresholds AFTER the all-zero early-out: on real content most
1975+ // edges filter nothing, and computing α/β/tc0 (two clamps plus
1976+ // three table loads, and a neighbour QP read on MB edges) for an
1977+ // edge we are about to skip is pure waste.
1978+ let qpav = if mb_edge {
1979+ (qpy(mb_x - 1, mb_y) + qpy(mb_x, mb_y) + 1) >> 1
1980+ } else {
1981+ qpy(mb_x, mb_y)
1982+ };
1983+ let (alpha_y, beta_y, tc0a) = thresholds(qpav, offset_a, offset_b);
1984+ let tc0_luma = |bs: i32| if (1..4).contains(&bs) { tc0a[bs as usize - 1] } else { 0 };
1985+ let x = mb_x * 16 + be * 4;
1986+ // Vertical edge via openh264's transpose → V-filter → transpose-back
1987+ // (the `DeblockLumaLt4H` wrapper). tc per 4-row segment (−1 = skip).
1988+ #[cfg(accel)]
1989+ {
1990+ let base = mb_y * 16 * cw + (x - 4); // p3 column, top row
1991+ if bs4.iter().all(|&b| b == 4) {
1992+ rusty_h264_accel::deblock_luma_eq4_h(&mut y[base..], cw, alpha_y, beta_y);
1993+ } else {
1994+ let tc: [i8; 4] = std::array::from_fn(|i| {
1995+ if (1..4).contains(&bs4[i]) { tc0_luma(bs4[i]) as i8 } else { -1 }
1996+ });
1997+ rusty_h264_accel::deblock_luma_lt4_h(&mut y[base..], cw, alpha_y, beta_y, &tc);
1998+ }
1999+ }
2000+ #[cfg(not(accel))]
vendor/rusty_h264-common/src/inter.rsadded+1899 -0
@@ -0,0 +1,1899 @@
1+//! Inter prediction primitives: motion compensation and motion-vector
2+//! prediction. Shared by the encoder (reconstruction) and decoder so the two
3+//! agree bit-for-bit. Motion vectors are in quarter-pel units; phase 4b uses
4+//! the integer part only (full-pel), with the 6-tap/bilinear sub-pel filters
5+//! arriving in 4c.
6+
7+/// Median of three values (`a + b + c − min − max`).
8+#[inline]
9+pub fn median3(a: i32, b: i32, c: i32) -> i32 {
10+ a + b + c - a.min(b).min(c) - a.max(b).max(c)
11+}
12+
13+/// A motion-vector predictor neighbor: whether the neighbor block is available
14+/// (inside the picture/decoded), its motion vector, and its reference index
15+/// (`-1` for intra/unavailable neighbors, which contribute a zero MV with a
16+/// non-matching reference).
17+#[derive(Clone, Copy)]
18+pub struct MvNeighbor {
19+ pub available: bool,
20+ pub mv: (i32, i32),
21+ pub ref_idx: i32,
22+}
23+
24+impl MvNeighbor {
25+ pub const NONE: MvNeighbor = MvNeighbor {
26+ available: false,
27+ mv: (0, 0),
28+ ref_idx: -1,
29+ };
30+}
31+
32+/// Median motion-vector prediction for a partition (spec §8.4.1.3.1), against
33+/// the current partition's reference `cur_ref`. `a`/`b`/`c` are the left, above,
34+/// and above-right neighbors. If exactly one neighbor shares `cur_ref`, its MV is
35+/// the predictor; otherwise the component-wise median is used.
36+pub fn predict_mv(a: MvNeighbor, b: MvNeighbor, c: MvNeighbor, cur_ref: i32) -> (i32, i32) {
37+ // Per-neighbor (mv, refIdx): a usable inter neighbor keeps its mv+ref, else
38+ // a zero MV with ref −1 (never matches a valid `cur_ref` ≥ 0).
39+ let resolve = |n: MvNeighbor| -> ((i32, i32), i32) {
40+ if n.available && n.ref_idx >= 0 {
41+ (n.mv, n.ref_idx)
42+ } else {
43+ ((0, 0), -1)
44+ }
45+ };
46+ let (mva, ra) = resolve(a);
47+ let (mut mvb, mut rb) = resolve(b);
48+ let (mut mvc, mut rc) = resolve(c);
49+
50+ // If both B and C are unavailable but A is available, B and C take A.
51+ if !b.available && !c.available && a.available {
52+ mvb = mva;
53+ rb = ra;
54+ mvc = mva;
55+ rc = ra;
56+ }
57+
58+ let matches = (ra == cur_ref) as i32 + (rb == cur_ref) as i32 + (rc == cur_ref) as i32;
59+ if matches == 1 {
60+ if ra == cur_ref {
61+ mva
62+ } else if rb == cur_ref {
63+ mvb
64+ } else {
65+ mvc
66+ }
67+ } else {
68+ (median3(mva.0, mvb.0, mvc.0), median3(mva.1, mvb.1, mvc.1))
69+ }
70+}
71+
72+/// Directional MV prediction for a sub-partition (spec §8.4.1.3.2) against the
73+/// partition's reference `cur_ref`. `mode` is the inter `mb_type` (0 = 16×16,
74+/// 1 = 16×8, 2 = 8×16). 16×8/8×16 use a specific neighbor directly when it shares
75+/// `cur_ref`; otherwise (and always for 16×16) the median.
76+pub fn predict_partition_mv(
77+ mode: u8,
78+ part: usize,
79+ a: MvNeighbor,
80+ b: MvNeighbor,
81+ c: MvNeighbor,
82+ cur_ref: i32,
83+) -> (i32, i32) {
84+ let m = |n: MvNeighbor| n.available && n.ref_idx == cur_ref;
85+ match (mode, part) {
86+ (1, 0) if m(b) => b.mv, // 16×8 top → above
87+ (1, 1) if m(a) => a.mv, // 16×8 bottom → left
88+ (2, 0) if m(a) => a.mv, // 8×16 left → left
89+ (2, 1) if m(c) => c.mv, // 8×16 right → above-right
90+ _ => predict_mv(a, b, c, cur_ref),
91+ }
92+}
93+
94+/// Inter `mb_type` → luma partition regions `(x, y, w, h)` in samples.
95+pub fn inter_partitions(mode: u8) -> &'static [(usize, usize, usize, usize)] {
96+ match mode {
97+ 1 => &[(0, 0, 16, 8), (0, 8, 16, 8)], // P_16x8
98+ 2 => &[(0, 0, 8, 16), (8, 0, 8, 16)], // P_8x16
99+ // P_8x8: four 8×8 sub-macroblocks in raster (decode_p8x8) order, each its
100+ // own MV. (Sub-8×8 shapes 8×4/4×8/4×4 within an 8×8 are a further split.)
101+ 3 => &[(0, 0, 8, 8), (8, 0, 8, 8), (0, 8, 8, 8), (8, 8, 8, 8)],
102+ _ => &[(0, 0, 16, 16)], // P_L0_16x16
103+ }
104+}
105+
106+/// Reference sample with edge clamping.
107+///
108+/// Bounds-SAFE: a decoder driven by a malformed stream can reach here with `(cw, ch)`
109+/// that do not match the plane it was handed, and every caller's "interior" test is
110+/// written against `cw`/`ch` rather than the slice length. In bounds this is identical
111+/// to a direct index; out of bounds it yields 0 instead of panicking. (Found by the
112+/// fuzzer the moment CABAC became the default — the CABAC parse produces wilder
113+/// vectors on mutated input than CAVLC did, so this path had never been reached.)
114+#[inline]
115+fn at(reference: &[u8], cw: usize, ch: usize, x: isize, y: isize) -> i32 {
116+ let xx = x.clamp(0, cw as isize - 1) as usize;
117+ let yy = y.clamp(0, ch as isize - 1) as usize;
118+ reference.get(yy * cw + xx).copied().unwrap_or(0) as i32
119+}
120+
121+#[inline]
122+fn clip_u8(v: i32) -> i32 {
123+ v.clamp(0, 255)
124+}
125+
126+/// Per-pixel quarter-pel luma sample (spec §8.4.2.2.1) — the readable reference
127+/// kept as the bit-exactness oracle for the block-kernel MC below.
128+#[cfg(test)]
129+fn luma_sample(reference: &[u8], cw: usize, ch: usize, ix: isize, iy: isize, fx: i32, fy: i32) -> i32 {
130+ let g = |dx: isize, dy: isize| at(reference, cw, ch, ix + dx, iy + dy);
131+ if fx == 0 && fy == 0 {
132+ return g(0, 0);
133+ }
134+ let hor6 = |dy: isize| g(-2, dy) - 5 * g(-1, dy) + 20 * g(0, dy) + 20 * g(1, dy) - 5 * g(2, dy) + g(3, dy);
135+ let ver6 = |dx: isize| g(dx, -2) - 5 * g(dx, -1) + 20 * g(dx, 0) + 20 * g(dx, 1) - 5 * g(dx, 2) + g(dx, 3);
136+ let b = || clip_u8((hor6(0) + 16) >> 5);
137+ let h = || clip_u8((ver6(0) + 16) >> 5);
138+ let m = || clip_u8((ver6(1) + 16) >> 5);
139+ let s = || clip_u8((hor6(1) + 16) >> 5);
140+ let j = || {
141+ let j1 = hor6(-2) - 5 * hor6(-1) + 20 * hor6(0) + 20 * hor6(1) - 5 * hor6(2) + hor6(3);
142+ clip_u8((j1 + 512) >> 10)
143+ };
144+ match (fx, fy) {
145+ (1, 0) => (g(0, 0) + b() + 1) >> 1,
146+ (2, 0) => b(),
147+ (3, 0) => (g(1, 0) + b() + 1) >> 1,
148+ (0, 1) => (g(0, 0) + h() + 1) >> 1,
149+ (1, 1) => (b() + h() + 1) >> 1,
150+ (2, 1) => (b() + j() + 1) >> 1,
151+ (3, 1) => (b() + m() + 1) >> 1,
152+ (0, 2) => h(),
153+ (1, 2) => (h() + j() + 1) >> 1,
154+ (2, 2) => j(),
155+ (3, 2) => (j() + m() + 1) >> 1,
156+ (0, 3) => (g(0, 1) + h() + 1) >> 1,
157+ (1, 3) => (h() + s() + 1) >> 1,
158+ (2, 3) => (j() + s() + 1) >> 1,
159+ _ => (m() + s() + 1) >> 1,
160+ }
161+}
162+
163+// ---- Block-level luma MC, mirroring openh264 `mc.cpp` (`McHorVerNN_c`) ----
164+//
165+// openh264 computes each half-pel plane once per block (not per pixel) and
166+// averages clipped planes for the quarter positions. Our `luma_sample` recomputed
167+// the 6-tap for every pixel; these kernels compute each plane once. Bit-identical:
168+// the 6-tap is separable with exact (un-rounded) integer intermediates, so
169+// horizontal-then-vertical equals vertical-then-horizontal, and the clamped tile
170+// reproduces `at()` exactly.
171+
172+/// Max luma interpolation tile: a 16×16 block plus the 6-tap halo (2 left/up,
173+/// 3 right/down) → 21×21.
174+const LUMA_TILE: usize = 21;
175+
176+/// Per-thread scratch for the sub-pel MC path.
177+///
178+/// These three buffers used to be created — and therefore **zero-initialised** —
179+/// inside every `mc_luma` call, and the tile was additionally returned *by value*.
180+/// That is ~1.4 KB of `memset` plus a 441-byte move per call, paid identically
181+/// whether the block is 16×16 (256 useful samples) or 4×4 (16). Profiling put
182+/// `inter-mc` at 166 s of a 266 s quality-preset encode over 991 M calls, and a
183+/// block-size sweep showed a 4×4 sub-pel call costing *more* than a 16×16 one
184+/// (248 vs 172 ns) — i.e. the cost was the per-call buffers, not the filter.
185+///
186+/// Hoisting them to thread-local scratch makes that setup once per thread instead
187+/// of once per candidate. Byte-identical: both `luma_tile_into` paths write the
188+/// whole `(bw+5)×(bh+5)` region before it is read, and `a`/`b` are written over
189+/// `bw*bh` samples by `luma_h`/`luma_v`/`luma_centre` before `pixel_avg`/`avg_full`
190+/// read the same range — so the zero-fill was dead in every case.
191+pub struct McScratch {
192+ tile: [u8; LUMA_TILE * LUMA_TILE],
193+ a: [u8; 256],
194+ b: [u8; 256],
195+}
196+
197+/// Runs `f` with the thread's MC scratch borrowed ONCE. Callers that issue many
198+/// MC calls in a row (the bi-pred pair, the P-path rect ladder) hoist the
199+/// TLS lookup + RefCell borrow out of the per-call path by taking this at
200+/// region/MB scope and calling `mc_luma_padded_pre` inside — that fixed
201+/// per-call cost is paid twice per bi-pred region, ~1M sub-pel calls per clip.
202+#[inline]
203+pub fn with_mc_scratch<R>(f: impl FnOnce(&mut McScratch) -> R) -> R {
204+ MC_SCRATCH.with(|s| f(&mut s.borrow_mut()))
205+}
206+
207+thread_local! {
208+ static MC_SCRATCH: core::cell::RefCell<McScratch> = const {
209+ core::cell::RefCell::new(McScratch {
210+ tile: [0; LUMA_TILE * LUMA_TILE],
211+ a: [0; 256],
212+ b: [0; 256],
213+ })
214+ };
215+}
216+
217+/// Dev-only census of `mc_luma` calls by block size × sub-pel phase.
218+///
219+/// Exists to size the half-pel-plane-cache lever: with a cached plane set, a
220+/// half-pel call becomes a strided COPY and a quarter-pel call a 2-tap AVERAGE,
221+/// so the prize is (how many calls are sub-pel) × (filter cost − read cost). The
222+/// mix is deterministic, so this is valid on a loaded machine.
223+#[cfg(feature = "profile")]
224+pub mod mcstats {
225+ use core::sync::atomic::{AtomicU64, Ordering};
226+
227+ /// Descent E depth-6: WHO calls `mc_luma`? `prof inter-mc` counts ~17 calls per
228+ /// macroblock while reconstruction needs only 1-4, so the stage is dominated by
229+ /// something other than recon and any prize computed against "recon MC" is priced
230+ /// on the wrong population. Callers tag themselves; 0 = untagged.
231+ pub const SITES: [&str; 5] = ["untagged", "recon", "search-fallback", "skip-check", "bdirect"];
232+ pub static SITE_COUNTS: [AtomicU64; 5] = [const { AtomicU64::new(0) }; 5];
233+ pub static SITE_CYCLES: [AtomicU64; 5] = [const { AtomicU64::new(0) }; 5];
234+ thread_local! {
235+ pub static SITE: core::cell::Cell<usize> = const { core::cell::Cell::new(0) };
236+ }
237+ /// Scoped tag: set on construction, restored on drop (call sites nest).
238+ pub struct SiteTag(usize);
239+ impl SiteTag {
240+ pub fn new(s: usize) -> Self {
241+ let prev = SITE.with(|c| c.replace(s));
242+ SiteTag(prev)
243+ }
244+ }
245+ impl Drop for SiteTag {
246+ fn drop(&mut self) {
247+ SITE.with(|c| c.set(self.0));
248+ }
249+ }
250+ #[inline]
251+ pub(super) fn site_add(c: u64) {
252+ let s = SITE.with(|c| c.get());
253+ SITE_COUNTS[s].fetch_add(1, Ordering::Relaxed);
254+ SITE_CYCLES[s].fetch_add(c, Ordering::Relaxed);
255+ }
256+ pub fn site_snapshot() -> Vec<(&'static str, u64, u64)> {
257+ (0..5).map(|i| (SITES[i], SITE_COUNTS[i].load(Ordering::Relaxed),
258+ SITE_CYCLES[i].load(Ordering::Relaxed))).collect()
259+ }
260+
261+ /// Phase classes: 0 = full-pel (0,0), 1 = half H/V, 2 = half centre (2,2),
262+ /// 3 = quarter (one component odd).
263+ pub const PHASES: [&str; 4] = ["fullpel", "half-HV", "half-ctr", "quarter"];
264+ /// Size classes: 16×16, 16×8/8×16, 8×8, 8×4/4×8, 4×4, other.
265+ pub const SIZES: [&str; 6] = ["16x16", "16x8/8x16", "8x8", "8x4/4x8", "4x4", "other"];
266+
267+ pub static COUNTS: [AtomicU64; 24] = [const { AtomicU64::new(0) }; 24];
268+ /// Descent E depth-6: CYCLES per bucket. A call-count census is the WRONG
269+ /// denominator for a prune — a full-pel 16x16 is a row copy, a quarter-pel is a
270+ /// per-pixel 6-tap, and they differ ~10x. Weight by time, not by calls.
271+ pub static CYCLES: [AtomicU64; 24] = [const { AtomicU64::new(0) }; 24];
272+
273+ #[inline]
274+ pub(super) fn bucket(bw: usize, bh: usize, fx: i32, fy: i32) -> usize {
275+ let size = match (bw, bh) {
276+ (16, 16) => 0,
277+ (16, 8) | (8, 16) => 1,
278+ (8, 8) => 2,
279+ (8, 4) | (4, 8) => 3,
280+ (4, 4) => 4,
281+ _ => 5,
282+ };
283+ let phase = match (fx, fy) {
284+ (0, 0) => 0,
285+ (2, 2) => 2,
286+ (fx, fy) if fx % 2 == 0 && fy % 2 == 0 => 1,
287+ _ => 3,
288+ };
289+ size * 4 + phase
290+ }
291+
292+ #[inline]
293+ pub(super) fn add_cycles(b: usize, c: u64) {
294+ CYCLES[b].fetch_add(c, Ordering::Relaxed);
295+ }
296+
297+ #[inline]
298+ pub(super) fn record(bw: usize, bh: usize, fx: i32, fy: i32) {
299+ let size = match (bw, bh) {
300+ (16, 16) => 0,
301+ (16, 8) | (8, 16) => 1,
302+ (8, 8) => 2,
303+ (8, 4) | (4, 8) => 3,
304+ (4, 4) => 4,
305+ _ => 5,
306+ };
307+ let phase = match (fx, fy) {
308+ (0, 0) => 0,
309+ (2, 2) => 2,
310+ (fx, fy) if fx % 2 == 0 && fy % 2 == 0 => 1,
311+ _ => 3,
312+ };
313+ COUNTS[size * 4 + phase].fetch_add(1, Ordering::Relaxed);
314+ }
315+
316+ pub fn reset() {
317+ for c in COUNTS.iter() {
318+ c.store(0, Ordering::Relaxed);
319+ }
320+ for c in CYCLES.iter() {
321+ c.store(0, Ordering::Relaxed);
322+ }
323+ for c in SITE_COUNTS.iter() {
324+ c.store(0, Ordering::Relaxed);
325+ }
326+ for c in SITE_CYCLES.iter() {
327+ c.store(0, Ordering::Relaxed);
328+ }
329+ }
330+
331+ /// `(size, phase, count, cycles)` for every non-empty bucket.
332+ pub fn snapshot_cycles() -> Vec<(&'static str, &'static str, u64, u64)> {
333+ let mut v = Vec::new();
334+ for i in 0..24 {
335+ let n = COUNTS[i].load(Ordering::Relaxed);
336+ if n != 0 {
337+ v.push((SIZES[i / 4], PHASES[i % 4], n, CYCLES[i].load(Ordering::Relaxed)));
338+ }
339+ }
340+ v
341+ }
342+
343+ /// `(size_label, phase_label, count)` for every non-empty bucket.
344+ pub fn snapshot() -> Vec<(&'static str, &'static str, u64)> {
345+ let mut v = Vec::new();
346+ for (i, c) in COUNTS.iter().enumerate() {
347+ let n = c.load(Ordering::Relaxed);
348+ if n > 0 {
349+ v.push((SIZES[i / 4], PHASES[i % 4], n));
350+ }
351+ }
352+ v
353+ }
354+}
355+
356+/// Extracts the `(bw+5)×(bh+5)` reference neighbourhood around the full-pel origin
357+/// `(ix0,iy0)` into `t`, clamping at the frame border — the edge-extended input
358+/// openh264's kernels assume. The block's top-left sample lands at tile `(2,2)`.
359+/// Returns the tile stride. Every sample in `[0, (bh+5)*ts)` is written.
360+fn luma_tile_into(
361+ t: &mut [u8],
362+ reference: &[u8],
363+ cw: usize,
364+ ch: usize,
365+ ix0: isize,
366+ iy0: isize,
367+ bw: usize,
368+ bh: usize,
369+) -> usize {
370+ let ts = bw + 5;
371+ // Interior fast path: the whole `(bw+5)×(bh+5)` halo is inside the frame, so no
372+ // edge clamp is needed. Extract by contiguous row copies (a vectorized memcpy)
373+ // — the unconditional per-pixel `clamp` on the slow path defeats
374+ // autovectorization even when (as here) it would always be a no-op.
375+ if ix0 - 2 >= 0
376+ && iy0 - 2 >= 0
377+ && ix0 - 2 + ts as isize <= cw as isize
378+ && iy0 - 2 + (bh + 5) as isize <= ch as isize
379+ && reference.len() >= cw * ch
380+ {
381+ let (rx0, ry0) = ((ix0 - 2) as usize, (iy0 - 2) as usize);
382+ for ty in 0..bh + 5 {
383+ let src = (ry0 + ty) * cw + rx0;
384+ t[ty * ts..ty * ts + ts].copy_from_slice(&reference[src..src + ts]);
385+ }
386+ return ts;
387+ }
388+ for ty in 0..bh + 5 {
389+ let ry = (iy0 - 2 + ty as isize).clamp(0, ch as isize - 1) as usize * cw;
390+ for tx in 0..ts {
391+ let rx = (ix0 - 2 + tx as isize).clamp(0, cw as isize - 1) as usize;
392+ t[ty * ts + tx] = reference.get(ry + rx).copied().unwrap_or(0);
393+ }
394+ }
395+ ts
396+}
397+
398+/// Horizontal half-pel plane (`McHorVer20`): `clip((6tapₕ + 16) >> 5)`, block
399+/// shifted by `(dr, dc)` tile rows/cols.
400+fn luma_h(t: &[u8], ts: usize, bw: usize, bh: usize, dr: usize, dc: usize, dst: &mut [u8]) {
401+ #[cfg(accel)]
402+ if bw == 16 || bw == 8 {
403+ rusty_h264_accel::mc_hor20(t, (2 + dr) * ts + 2 + dc, ts, dst, bw, bh);
404+ return;
405+ }
406+ for r in 0..bh {
407+ let base = (2 + r + dr) * ts + 2 + dc;
408+ for c in 0..bw {
409+ let p = base + c;
410+ let f = t[p - 2] as i32 - 5 * t[p - 1] as i32 + 20 * t[p] as i32 + 20 * t[p + 1] as i32
411+ - 5 * t[p + 2] as i32
412+ + t[p + 3] as i32;
413+ dst[r * bw + c] = clip_u8((f + 16) >> 5) as u8;
414+ }
415+ }
416+}
417+
418+/// Vertical half-pel plane (`McHorVer02`): `clip((6tapᵥ + 16) >> 5)`.
419+fn luma_v(t: &[u8], ts: usize, bw: usize, bh: usize, dr: usize, dc: usize, dst: &mut [u8]) {
420+ #[cfg(accel)]
421+ if bw == 16 || bw == 8 {
422+ rusty_h264_accel::mc_ver02(t, (2 + dr) * ts + 2 + dc, ts, dst, bw, bh);
423+ return;
424+ }
425+ for r in 0..bh {
426+ let base = (2 + r + dr) * ts + 2 + dc;
427+ for c in 0..bw {
428+ let p = base + c;
429+ let f = t[p - 2 * ts] as i32 - 5 * t[p - ts] as i32 + 20 * t[p] as i32
430+ + 20 * t[p + ts] as i32
431+ - 5 * t[p + 2 * ts] as i32
432+ + t[p + 3 * ts] as i32;
433+ dst[r * bw + c] = clip_u8((f + 16) >> 5) as u8;
434+ }
435+ }
436+}
437+
438+/// Centre half-pel plane (`McHorVer22`): vertical 6-tap to 16-bit intermediates,
439+/// then horizontal 6-tap — `clip((·+ 512) >> 10)`.
440+fn luma_centre(t: &[u8], ts: usize, bw: usize, bh: usize, dst: &mut [u8]) {
441+ #[cfg(accel)]
442+ if bw == 16 || bw == 8 {
443+ rusty_h264_accel::mc_centre(t, ts, dst, bw, bh);
444+ return;
445+ }
446+ let mut itmp = [0i32; LUMA_TILE];
447+ for r in 0..bh {
448+ let base = (2 + r) * ts;
449+ for (j, slot) in itmp[..bw + 5].iter_mut().enumerate() {
450+ let p = base + j;
451+ *slot = t[p - 2 * ts] as i32 - 5 * t[p - ts] as i32 + 20 * t[p] as i32
452+ + 20 * t[p + ts] as i32
453+ - 5 * t[p + 2 * ts] as i32
454+ + t[p + 3 * ts] as i32;
455+ }
456+ for c in 0..bw {
457+ let f = itmp[c] - 5 * itmp[c + 1] + 20 * itmp[c + 2] + 20 * itmp[c + 3] - 5 * itmp[c + 4]
458+ + itmp[c + 5];
459+ dst[r * bw + c] = clip_u8((f + 512) >> 10) as u8;
460+ }
461+ }
462+}
463+
464+/// `PixelAvg_c`: `(a + b + 1) >> 1` of two clipped planes.
465+fn pixel_avg(a: &[u8], b: &[u8], bw: usize, bh: usize, dst: &mut [u8]) {
466+ let n = bw * bh;
467+ // Same leak `avg_full` fixed, for the TWO-FILTER quarter positions
468+ // ((1,1)/(3,1)/(1,3)/(3,3) and the centre-adjacent four): the average on
469+ // top of the asm half-pel kernels was a scalar runtime-width loop. The MC
470+ // census prices quarter-pel at ~68% of decoder MC cycles, and the eight
471+ // positions served here all end in this loop. `pavgb` computes
472+ // `(a + b + 1) >> 1` exactly — byte-identical. The scalar loop stays as
473+ // the non-accel path and the oracle.
474+ //
475+ // The TRUE block geometry is passed, never reconstructed from `n`: the
476+ // openh264 row loops are unrolled by more than one row, so a synthetic
477+ // (16, n/16) shape with h < 4 over-runs the block — that was a real
478+ // SEGFAULT on every sub-8x8 stream (first cut of this dispatch, caught by
479+ // the corpus gate). The kernels are exercised at every real (bw, bh ≥ 4)
480+ // shape by `avg_full` already.
481+ #[cfg(accel)]
482+ if (bw == 16 || bw == 8 || bw == 4) && a.len() >= n && b.len() >= n && dst.len() >= n {
483+ rusty_h264_accel::pixel_avg(&mut dst[..n], &a[..n], bw, &b[..n], bw, bw, bh);
484+ return;
485+ }
486+ for i in 0..n {
487+ dst[i] = ((a[i] as i32 + b[i] as i32 + 1) >> 1) as u8;
488+ }
489+}
490+
491+/// `PixelAvg_c` of a half-pel plane with a full-pel block shifted by `(dr, dc)`.
492+fn avg_full(t: &[u8], ts: usize, bw: usize, bh: usize, dr: usize, dc: usize, half: &[u8], dst: &mut [u8]) {
493+ // The QUARTER-PEL step. `luma_h`/`luma_v`/`luma_centre` have been on asm for a
494+ // long time; this average layered on top of them stayed a scalar per-pixel loop
495+ // with a runtime width. On real x264 streams ~85% of decoder MC cycles are
496+ // quarter-pel, so this loop was handing the kernel's win back on the large
497+ // majority of MC. `pavgb` computes `(a + b + 1) >> 1` exactly — byte-identical.
498+ #[cfg(accel)]
499+ if bw == 16 || bw == 8 || bw == 4 {
500+ let base = (2 + dr) * ts + 2 + dc;
501+ rusty_h264_accel::pixel_avg(dst, &t[base..], ts, half, bw, bw, bh);
502+ return;
503+ }
504+ for r in 0..bh {
505+ let base = (2 + r + dr) * ts + 2 + dc;
506+ for c in 0..bw {
507+ dst[r * bw + c] = ((t[base + c] as i32 + half[r * bw + c] as i32 + 1) >> 1) as u8;
508+ }
509+ }
510+}
511+
512+/// A/B: restore half→scratch→avg compose for one-filter qpel (`RS_H264_QPEL_COMPOSE=1`).
513+#[inline]
514+fn qpel_compose() -> bool {
515+ use std::sync::OnceLock;
516+ static V: OnceLock<bool> = OnceLock::new();
517+ *V.get_or_init(|| std::env::var_os("RS_H264_QPEL_COMPOSE").is_some_and(|v| v == "1"))
518+}
519+
520+/// One-filter qpel (`(1,0)/(3,0)/(0,1)/(0,3)`): fused half+avg when accel + w∈{8,16}.
521+/// `horiz`: horizontal 6-tap; else vertical. `fshift`: full-pel offset (0 or 1) in the
522+/// filter axis (`fdc` for horiz, `fdr` for vert) — matches `avg_full`'s (0,1)/(1,0).
523+fn qpel_one_filter(
524+ t: &[u8],
525+ ts: usize,
526+ bw: usize,
527+ bh: usize,
528+ horiz: bool,
529+ fshift: usize,
530+ out: &mut [u8],
531+) {
532+ #[cfg(accel)]
533+ if !qpel_compose() && (bw == 16 || bw == 8) {
534+ let off = 2 * ts + 2;
535+ if horiz {
536+ rusty_h264_accel::mc_hor_qpel(t, off, ts, out, bw, bh, fshift);
537+ } else {
538+ rusty_h264_accel::mc_ver_qpel(t, off, ts, out, bw, bh, fshift);
539+ }
540+ return;
541+ }
542+ // Compose oracle / narrow widths / non-accel: half into a stack scratch, then avg.
543+ let mut half = [0u8; 256];
544+ let n = bw * bh;
545+ debug_assert!(n <= 256);
546+ if horiz {
547+ luma_h(t, ts, bw, bh, 0, 0, &mut half[..n]);
548+ avg_full(t, ts, bw, bh, 0, fshift, &half[..n], out);
549+ } else {
550+ luma_v(t, ts, bw, bh, 0, 0, &mut half[..n]);
551+ avg_full(t, ts, bw, bh, fshift, 0, &half[..n], out);
552+ }
553+}
554+
555+/// Two-filter HV qpel: horizontal half into `a`, then vertical half+avg into `out`
556+/// (kills the second scratch store). Compose oracle when `qpel_compose()`.
557+fn qpel_hv(
558+ t: &[u8],
559+ ts: usize,
560+ bw: usize,
561+ bh: usize,
562+ hdr: usize,
563+ hdc: usize,
564+ vdr: usize,
565+ vdc: usize,
566+ a: &mut [u8],
567+ out: &mut [u8],
568+) {
569+ luma_h(t, ts, bw, bh, hdr, hdc, a);
570+ #[cfg(accel)]
571+ if !qpel_compose() && (bw == 16 || bw == 8) {
572+ let off = (2 + vdr) * ts + 2 + vdc;
573+ rusty_h264_accel::mc_ver02_avg(t, off, ts, out, bw, bh, a, bw);
574+ return;
575+ }
576+ let n = bw * bh;
577+ let mut b = [0u8; 256];
578+ debug_assert!(n <= 256);
579+ luma_v(t, ts, bw, bh, vdr, vdc, &mut b[..n]);
580+ pixel_avg(a, &b[..n], bw, bh, out);
581+}
582+
583+/// The `McLuma_c` `[mvx&3][mvy&3]` dispatch over the clamped tile (sub-pel only;
584+/// `(0,0)` is handled by the full-pel copy path in [`mc_luma`]).
585+#[allow(clippy::too_many_arguments)]
586+fn mc_luma_subpel(
587+ t: &[u8],
588+ ts: usize,
589+ bw: usize,
590+ bh: usize,
591+ fx: i32,
592+ fy: i32,
593+ a: &mut [u8],
594+ b: &mut [u8],
595+ out: &mut [u8],
596+) {
597+ // `a`/`b` are caller-owned scratch (see `McScratch`): every arm below fully
598+ // writes the `n` samples it later reads, so their prior contents are dead.
599+ // One-filter qpel no longer needs them when fused (see `qpel_one_filter`).
600+ match (fx, fy) {
601+ (2, 0) => luma_h(t, ts, bw, bh, 0, 0, out),
602+ (0, 2) => luma_v(t, ts, bw, bh, 0, 0, out),
603+ (2, 2) => luma_centre(t, ts, bw, bh, out),
604+ // One-filter qpel: fuse half-pel + pavgb (openh264 McHorVer10/30/01/03).
605+ // Compose path (`RS_H264_QPEL_COMPOSE=1`) keeps the scratch store as A/B oracle.
606+ (1, 0) => qpel_one_filter(t, ts, bw, bh, true, 0, out),
607+ (3, 0) => qpel_one_filter(t, ts, bw, bh, true, 1, out),
608+ (0, 1) => qpel_one_filter(t, ts, bw, bh, false, 0, out),
609+ (0, 3) => qpel_one_filter(t, ts, bw, bh, false, 1, out),
610+ (1, 1) => qpel_hv(t, ts, bw, bh, 0, 0, 0, 0, a, out),
611+ (3, 1) => qpel_hv(t, ts, bw, bh, 0, 0, 0, 1, a, out),
612+ (1, 3) => qpel_hv(t, ts, bw, bh, 1, 0, 0, 0, a, out),
613+ (3, 3) => qpel_hv(t, ts, bw, bh, 1, 0, 0, 1, a, out),
614+ (2, 1) => {
615+ luma_h(t, ts, bw, bh, 0, 0, a);
616+ luma_centre(t, ts, bw, bh, b);
617+ pixel_avg(a, b, bw, bh, out);
618+ }
619+ (2, 3) => {
620+ luma_h(t, ts, bw, bh, 1, 0, a);
621+ luma_centre(t, ts, bw, bh, b);
622+ pixel_avg(a, b, bw, bh, out);
623+ }
624+ (1, 2) => {
625+ luma_v(t, ts, bw, bh, 0, 0, a);
626+ luma_centre(t, ts, bw, bh, b);
627+ pixel_avg(a, b, bw, bh, out);
628+ }
629+ (3, 2) => {
630+ luma_v(t, ts, bw, bh, 0, 1, a);
631+ luma_centre(t, ts, bw, bh, b);
632+ pixel_avg(a, b, bw, bh, out);
633+ }
634+ _ => unreachable!("(0,0) is the full-pel path"),
635+ }
636+}
637+
638+/// The three half-pel luma planes of one reference picture, at full frame size.
639+///
640+/// x264 filters these ONCE per reference frame and then every sub-pel motion-search
641+/// candidate is a strided copy from one plane (half positions) or a 2-tap average of
642+/// two (quarter positions). We previously re-ran the 6-tap per candidate: measured at
643+/// 166 s of a 266 s quality-preset encode over 991 M calls, against x264's 188 ms of
644+/// `hpel-filter` for the entire corpus.
645+///
646+/// Naming follows the spec's sample grid at full-pel `G`:
647+/// `h` = `b` (half-pel horizontal) · `v` = `h` (half-pel vertical) · `c` = `j` (centre)
648+#[derive(Clone, Debug)]
649+pub struct HpelPlanes {
650+ /// Edge-replicated FULL-pel plane. Needed as an operand for the quarter
651+ /// positions that average against `G`, and padded so out-of-frame candidates
652+ /// resolve without a bounds decline.
653+ pub f: Vec<u8>,
654+ pub h: Vec<u8>,
655+ pub v: Vec<u8>,
656+ pub c: Vec<u8>,
657+ /// Row stride of every plane (`cw + 2*HPEL_PAD`).
658+ pub stride: usize,
659+ pub pad: usize,
660+ pub pw: usize,
661+ pub ph: usize,
662+ pub cw: usize,
663+ pub ch: usize,
664+}
665+
666+/// Border added to every cached plane, in samples.
667+///
668+/// Sized so a ±24 motion search around any macroblock still lands inside: a 16-wide
669+/// block at the right edge reaches `cw + 24`, and reading its `+1` neighbour needs
670+/// `cw + 41` ≤ `cw + PAD`. Without a border the plane cache DECLINED every candidate
671+/// whose vector left the picture — 62.5% of the remaining `mc_luma` fallbacks, at
672+/// ~195 ns against 33 ns for a plane read.
673+///
674+/// SWEPT (foreman / bus / park_joy, `RFF_HPEL_PAD`), because a bigger border is a
675+/// TRADE — more candidates covered, but a larger working set (4 planes over
676+/// `(cw+2P)(ch+2P)`) and a costlier per-frame build:
677+///
678+/// | pad | foreman fallbacks | bus | park_joy | build (foreman) |
679+/// |---|---|---|---|---|
680+/// | 0 | 207,537 | 838,581 | 6,354,258 | 5.7 ms |
681+/// | 8 | 127,407 | 774,592 | 6,172,777 | 4.8 ms |
682+/// | **16** | **127,274** | **765,625** | **6,122,122** | **6.1 ms** |
683+/// | 32 | 127,262 | 764,999 | 6,093,358 | 9.0 ms |
684+///
685+/// Padding replicated around each cached half-pel plane.
686+///
687+/// 32, raised from 16 after the edge full-pel path landed. The earlier sweep found the
688+/// pad made NO difference and was correctly recorded as refuted -- but that measurement
689+/// ran against a population dominated by FULL-PEL declines, which `hpel_ref` now serves.
690+/// The refutation expired when its baseline moved. Re-swept, pad 32 removes essentially
691+/// every remaining search fallback (football 17,662 -> 175, foreman 3,238 -> 0).
692+///
693+/// Priced at the PIPELINE level, not by component arithmetic -- the component estimate
694+/// was wrong in both directions (it mixed an rdtsc cycle census with profiler
695+/// milliseconds via an assumed clock, and read a 23-sample build cost off single runs).
696+/// Paired ABBA, median of paired ratios: bus 1.113x (14/14), blue_sky 1.054x (6/6),
697+/// park_joy 1.050x (11/12), football 1.026x (11/14), foreman 1.015x (ns),
698+/// crowd_run 1.005x (ns). No clip regresses; the gain tracks edge-overhang density, so
699+/// fast pans benefit most and large frames least.
700+///
701+/// Byte-identical at 16/32/64 -- a wider pad grows the planes but never changes a value
702+/// read. `RFF_HPEL_PAD` overrides.
703+pub const HPEL_PAD_DEFAULT: usize = 32;
704+pub fn hpel_pad() -> usize {
705+ use std::sync::OnceLock;
706+ static P: OnceLock<usize> = OnceLock::new();
707+ *P.get_or_init(|| {
708+ std::env::var("RFF_HPEL_PAD")
709+ .ok()
710+ .and_then(|s| s.parse().ok())
711+ .unwrap_or(HPEL_PAD_DEFAULT)
712+ .clamp(0, 128)
713+ })
714+}
715+
716+/// Builds the three half-pel planes for `reference` (`cw`×`ch`, MB-aligned).
717+///
718+/// Bit-exact with [`mc_luma`] by CONSTRUCTION: it walks the frame in the same 16×16
719+/// blocks, extracts the same clamped halo via [`luma_tile_into`], and runs the same
720+/// `luma_h`/`luma_v`/`luma_centre` kernels. Each output sample depends only on the
721+/// six clamped input samples around it, so the value is independent of which block
722+/// computed it.
723+/// Edge-replicates a `w`×`h` plane into a `(w+2·pad)`×`(h+2·pad)` padded copy —
724+/// openh264's `ExpandPicture`. `mc_luma` clamps each tap independently via `at()`,
725+/// and clamping IS edge replication, so filtering the padded plane is bit-identical
726+/// to the clamped-read original (the argument `build_hpel_planes` rests on; the
727+/// decoder's per-reference padding reuses it so per-MC-call tile extraction dies).
728+pub fn pad_plane(src: &[u8], w: usize, h: usize, pad: usize) -> Vec<u8> {
729+ pad_plane_into(Vec::new(), src, w, h, pad)
730+}
731+
732+/// `pad_plane` reusing a recycled buffer. Every byte of the padded plane is
733+/// written by the row loop below (left fill + interior copy + right fill, all
734+/// `ph` rows), so a RIGHT-SIZED recycled buffer needs no clearing at all — and,
735+/// unlike a fresh `vec![0; n]` (whose zero pages are free but whose first
736+/// touches page-fault), its pages are already mapped and warm. This is what the
737+/// earlier pad_plane memset-elimination attempt (refuted, WHYS ledger) was
738+/// missing: on a FRESH alloc the memset is free; the win only exists when the
739+/// allocation itself is recycled.
740+pub fn pad_plane_into(mut f: Vec<u8>, src: &[u8], w: usize, h: usize, pad: usize) -> Vec<u8> {
741+ let (pw, ph) = (w + 2 * pad, h + 2 * pad);
742+ if f.len() != pw * ph {
743+ f.clear();
744+ f.resize(pw * ph, 0);
745+ }
746+ for y in 0..ph {
747+ let sy = (y as isize - pad as isize).clamp(0, h as isize - 1) as usize;
748+ let row = &src[sy * w..sy * w + w];
749+ let d = &mut f[y * pw..y * pw + pw];
750+ d[..pad].fill(row[0]);
751+ d[pad..pad + w].copy_from_slice(row);
752+ d[pad + w..].fill(row[w - 1]);
753+ }
754+ f
755+}
756+
757+pub fn build_hpel_planes(reference: &[u8], cw: usize, ch: usize) -> HpelPlanes {
758+ let _g = crate::prof::scope(crate::prof::Stage::MeHpelBuild);
759+ let pad = hpel_pad();
760+ let (pw, ph) = (cw + 2 * pad, ch + 2 * pad);
761+ // 1. Edge-replicated source (see `pad_plane` for why this is bit-identical).
762+ let f = pad_plane(reference, cw, ch, pad);
763+ // 2. Filter the three half-pel planes over the padded area.
764+ let mut h = vec![0u8; pw * ph];
765+ let mut v = vec![0u8; pw * ph];
766+ let mut c = vec![0u8; pw * ph];
767+ // Dispatch ladder: the AVX2 FUSED single pass (side-by-side descent: the tile
768+ // walk measured 8× x264's hpel-filter, whose fused shape this kernel mirrors)
769+ // → env-forced scalar fused (RFF_HPEL_FUSED=1, the oracle base) → tile walk.
770+ // All three are byte-identical (`fused_hpel_builder_matches_tiles`,
771+ // `avx2_fused_matches_scalar_fused`); the choice is speed only.
772+ #[cfg(accel)]
773+ let done = !hpel_fused_forced_off() && rusty_h264_accel::hpel_fused(&f, pw, ph, &mut h, &mut v, &mut c);
774+ #[cfg(not(accel))]
775+ let done = false;
776+ if !done {
777+ if hpel_fused_enabled() {
778+ build_hpel_fused(&f, pw, ph, &mut h, &mut v, &mut c);
779+ } else {
780+ build_hpel_tiles(&f, pw, ph, &mut h, &mut v, &mut c);
781+ }
782+ }
783+ HpelPlanes { f, h, v, c, stride: pw, pad, pw, ph, cw, ch }
784+}
785+
786+/// Campaign-3 knob. DEFAULT OFF (the tile walk): the scalar fused pass measured
787+/// SLOWER than the tile walk (950 vs 617 µs/frame CIF) because the tiles run the
788+/// SSE2/AVX2 `mc_hor20/ver02/centre` asm kernels — their throughput beats the
789+/// fused pass's redundancy savings. The fused builder + its byte-identity oracle
790+/// stay in-tree as the base for a future AVX2 fused kernel (`RFF_HPEL_FUSED=1`),
791+/// which is the only shape that can beat the tiles.
792+fn hpel_fused_enabled() -> bool {
793+ use std::sync::OnceLock;
794+ static E: OnceLock<bool> = OnceLock::new();
795+ *E.get_or_init(|| std::env::var("RFF_HPEL_FUSED").map(|s| s == "1").unwrap_or(false))
796+}
797+
798+/// `RFF_HPEL_AVX2=0` pins the pre-kernel path (tile walk / scalar fused) for A/B —
799+/// the AVX2 fused pass is byte-identical, so this is a speed-experiment knob only.
800+#[cfg(accel)]
801+fn hpel_fused_forced_off() -> bool {
802+ use std::sync::OnceLock;
803+ static E: OnceLock<bool> = OnceLock::new();
804+ *E.get_or_init(|| std::env::var("RFF_HPEL_AVX2").map(|s| s == "0").unwrap_or(false))
805+}
806+
807+/// The ORIGINAL builder — walks 16×16 tiles through `luma_tile_into` + the MC
808+/// kernels. Kept as the fused builder's oracle and the `RFF_HPEL_FUSED=0` path.
809+fn build_hpel_tiles(f: &[u8], pw: usize, ph: usize, h: &mut [u8], v: &mut [u8], c: &mut [u8]) {
810+ let mut tile = [0u8; LUMA_TILE * LUMA_TILE];
811+ let mut blk = [0u8; 256];
812+ let mut by = 0;
813+ while by < ph {
814+ let mut bx = 0;
815+ while bx < pw {
816+ let bh = 16.min(ph - by);
817+ let bwid = 16.min(pw - bx);
818+ let ts = luma_tile_into(&mut tile, f, pw, ph, bx as isize, by as isize, bwid, bh);
819+ for kind in 0u8..3 {
820+ let plane: &mut [u8] = match kind {
821+ 0 => &mut *h,
822+ 1 => &mut *v,
823+ _ => &mut *c,
824+ };
825+ match kind {
826+ 0 => luma_h(&tile, ts, bwid, bh, 0, 0, &mut blk),
827+ 1 => luma_v(&tile, ts, bwid, bh, 0, 0, &mut blk),
828+ _ => luma_centre(&tile, ts, bwid, bh, &mut blk),
829+ }
830+ for r in 0..bh {
831+ plane[(by + r) * pw + bx..][..bwid].copy_from_slice(&blk[r * bwid..][..bwid]);
832+ }
833+ }
834+ bx += 16;
835+ }
836+ by += 16;
837+ }
838+}
839+
840+/// Campaign 3 (lets-win-optimize.md): the FUSED single-pass builder — x264's
841+/// `hpel_filter` shape. The tile walk re-extracts a `(16+5)²` halo per 16×16 block
842+/// (1.7× redundant reads), re-runs per-tile dispatch, and copies each block out
843+/// three times; this pass reads each source row band once and writes H, V, C
844+/// directly. BYTE-IDENTICAL to the tile builder: the same 6-tap integer formulas
845+/// over the same clamped `f` samples (interior rows/cols never clamp; the ±2/3
846+/// borders of the padded plane clamp exactly like `luma_tile_into`'s halo does),
847+/// and the centre's i32 vertical intermediates reproduce `luma_centre`'s order.
848+/// Pinned by `fused_hpel_builder_matches_tiles`.
849+fn build_hpel_fused(f: &[u8], pw: usize, ph: usize, h: &mut [u8], v: &mut [u8], c: &mut [u8]) {
850+ let cl = |i: isize, hi: usize| i.clamp(0, hi as isize - 1) as usize;
851+ // Extended per-row buffers: index j covers column j-2 (clamped into the plane).
852+ let mut vt = vec![0i32; pw + 5]; // vertical 6-tap intermediates (unrounded)
853+ let mut hb = vec![0u8; pw + 5]; // this row's source with clamped column halo
854+ for y in 0..ph {
855+ let (ym2, ym1, y0, yp1, yp2, yp3) = (
856+ cl(y as isize - 2, ph) * pw,
857+ cl(y as isize - 1, ph) * pw,
858+ y * pw,
859+ cl(y as isize + 1, ph) * pw,
860+ cl(y as isize + 2, ph) * pw,
861+ cl(y as isize + 3, ph) * pw,
862+ );
863+ // Column-clamped borders (≤5 samples each side); the interior runs with
864+ // DIRECT indices — a per-element clamp in this loop defeats
865+ // autovectorization and measured the whole builder 2.2× slower.
866+ for j in 0..2 {
867+ let x = 0usize;
868+ vt[j] = f[ym2 + x] as i32 - 5 * f[ym1 + x] as i32 + 20 * f[y0 + x] as i32
869+ + 20 * f[yp1 + x] as i32
870+ - 5 * f[yp2 + x] as i32
871+ + f[yp3 + x] as i32;
872+ hb[j] = f[y0 + x];
873+ }
874+ for j in 2..pw + 2 {
875+ let x = j - 2;
876+ vt[j] = f[ym2 + x] as i32 - 5 * f[ym1 + x] as i32 + 20 * f[y0 + x] as i32
877+ + 20 * f[yp1 + x] as i32
878+ - 5 * f[yp2 + x] as i32
879+ + f[yp3 + x] as i32;
880+ hb[j] = f[y0 + x];
881+ }
882+ for j in pw + 2..pw + 5 {
883+ let x = pw - 1;
884+ vt[j] = f[ym2 + x] as i32 - 5 * f[ym1 + x] as i32 + 20 * f[y0 + x] as i32
885+ + 20 * f[yp1 + x] as i32
886+ - 5 * f[yp2 + x] as i32
887+ + f[yp3 + x] as i32;
888+ hb[j] = f[y0 + x];
889+ }
890+ let hrow = &mut h[y0..y0 + pw];
891+ let vrow = &mut v[y0..y0 + pw];
892+ let crow = &mut c[y0..y0 + pw];
893+ for x in 0..pw {
894+ vrow[x] = clip_u8((vt[x + 2] + 16) >> 5) as u8;
895+ }
896+ for x in 0..pw {
897+ let s = vt[x] - 5 * vt[x + 1] + 20 * vt[x + 2] + 20 * vt[x + 3] - 5 * vt[x + 4]
898+ + vt[x + 5];
899+ crow[x] = clip_u8((s + 512) >> 10) as u8;
900+ }
901+ for x in 0..pw {
902+ let s = hb[x] as i32 - 5 * hb[x + 1] as i32 + 20 * hb[x + 2] as i32
903+ + 20 * hb[x + 3] as i32
904+ - 5 * hb[x + 4] as i32
905+ + hb[x + 5] as i32;
906+ hrow[x] = clip_u8((s + 16) >> 5) as u8;
907+ }
908+ }
909+}
910+
911+/// Fills `out` with the `bw`×`bh` sub-pel prediction read from cached planes.
912+///
913+/// Returns `false` when the access (which may reach one sample past the block on
914+/// either axis, for the `m`/`s` neighbours) is not fully interior — the caller then
915+/// falls back to [`mc_luma`]. Bit-identical to `mc_luma` wherever it returns `true`:
916+/// each arm below is the same pair of operands `mc_luma_subpel` averages.
917+#[allow(clippy::too_many_arguments)]
918+/// Descent C: half-pel (single-plane, copy-free-able) vs quarter-pel (two-plane average).
919+#[cfg(feature = "profile")]
920+pub mod hpelphase {
921+ use core::sync::atomic::{AtomicU64, Ordering};
922+ pub static C: [AtomicU64; 2] = [const { AtomicU64::new(0) }; 2];
923+ #[inline]
924+ pub fn bump(i: usize) { C[i].fetch_add(1, Ordering::Relaxed); }
925+ pub fn reset() { for c in C.iter() { c.store(0, Ordering::Relaxed); } }
926+ pub fn snapshot() -> Vec<u64> { C.iter().map(|c| c.load(Ordering::Relaxed)).collect() }
927+}
928+
929+/// Descent C: the SINGLE-PLANE (half-pel) phases — (2,0)->h, (0,2)->v, (2,2)->c —
930+/// are already contiguous at plane stride, exactly like the interior full-pel case.
931+/// Hand the consumer `(plane, base, stride)` so it can read them IN PLACE rather than
932+/// copy 256 bytes into a temp first. Byte-identical to `hpel_block` by construction:
933+/// same plane, same base, same samples — only the copy is elided.
934+/// Returns `None` for quarter-pel (a two-plane average, which must be materialized),
935+/// for out-of-range coordinates, and whenever `hpel_block` would decline.
936+#[inline]
937+pub fn hpel_ref<'a>(
938+ p: &'a HpelPlanes,
939+ x0: usize,
940+ y0: usize,
941+ bw: usize,
942+ bh: usize,
943+ mvx: i32,
944+ mvy: i32,
945+) -> Option<(&'a [u8], usize, usize)> {
946+ let (fx, fy) = (mvx & 3, mvy & 3);
947+ let plane = match (fx, fy) {
948+ (2, 0) => &p.h,
949+ (0, 2) => &p.v,
950+ (2, 2) => &p.c,
951+ // Descent E: FULL-PEL off the frame edge. `hpel_block` declines these before its
952+ // bounds check ("the full-pel copy path is already optimal"), so the caller fell
953+ // back to a per-pixel clamped `mc_luma` -- measured at 76-79% of all mc_luma
954+ // TIME, the single largest consumer of that stage. But `f` IS the padded,
955+ // edge-replicated reference, so it reproduces mc_luma's clamp exactly and can be
956+ // read in place like any other phase. (Widening the pad does NOT fix this: the
957+ // decline count is identical at pad 16 and pad 64 -- it was never a bounds issue.)
958+ (0, 0) => &p.f,
959+ _ => return None,
960+ };
961+ let (ix0, iy0) = (x0 as isize + (mvx >> 2) as isize, y0 as isize + (mvy >> 2) as isize);
962+ let (px, py) = (ix0 + p.pad as isize, iy0 + p.pad as isize);
963+ // Identical guard to `hpel_block`, including its `+1` slack, so the two paths
964+ // accept exactly the same candidate set (no bitstream drift from a wider path).
965+ if px < 0 || py < 0 || px + bw as isize + 1 > p.pw as isize || py + bh as isize + 1 > p.ph as isize {
966+ return None;
967+ }
968+ let base = py as usize * p.stride + px as usize;
969+ if base + (bh - 1) * p.stride + bw > plane.len() {
970+ return None;
971+ }
972+ Some((plane, base, p.stride))
973+}
974+
975+/// Challenge-1 A3: the QUARTER-pel companion of [`hpel_ref`] — resolves the two
976+/// plane operands whose `(a+b+1)>>1` average IS the prediction, so the ME cost can
977+/// be one fused avg+SATD kernel pass instead of materialize-256-bytes-then-SATD.
978+/// Same bounds guard as [`hpel_block`] (identical accepted-candidate set); returns
979+/// `(plane_a, base_a, plane_b, base_b, stride)`. `None` for non-quarter phases
980+/// (those are [`hpel_ref`]'s) and whenever `hpel_block` would decline.
981+#[inline]
982+pub fn hpel_qpel_refs<'a>(
983+ p: &'a HpelPlanes,
984+ x0: usize,
985+ y0: usize,
986+ bw: usize,
987+ bh: usize,
988+ mvx: i32,
989+ mvy: i32,
990+) -> Option<(&'a [u8], usize, &'a [u8], usize, usize)> {
991+ let (fx, fy) = (mvx & 3, mvy & 3);
992+ // Quarter phases only: at least one fractional part is odd.
993+ if fx & 1 == 0 && fy & 1 == 0 {
994+ return None;
995+ }
996+ let (ix0, iy0) = (x0 as isize + (mvx >> 2) as isize, y0 as isize + (mvy >> 2) as isize);
997+ let (px, py) = (ix0 + p.pad as isize, iy0 + p.pad as isize);
998+ if px < 0 || py < 0 || px + bw as isize + 1 > p.pw as isize || py + bh as isize + 1 > p.ph as isize {
999+ return None;
1000+ }
1001+ let stride = p.stride;
1002+ let base = py as usize * stride + px as usize;
1003+ let g: &[u8] = &p.f;
1004+ // The SAME operand table as `hpel_block`'s quarter arm (the spec's `m`/`s`
1005+ // neighbour shifts baked into the base offsets).
1006+ let (pa, oa, pb, ob): (&[u8], usize, &[u8], usize) = match (fx, fy) {
1007+ (1, 0) => (g, 0, &p.h, 0),
1008+ (3, 0) => (g, 1, &p.h, 0),
1009+ (0, 1) => (g, 0, &p.v, 0),
1010+ (0, 3) => (g, stride, &p.v, 0),
1011+ (1, 1) => (&p.h, 0, &p.v, 0),
1012+ (3, 1) => (&p.h, 0, &p.v, 1),
1013+ (1, 3) => (&p.h, stride, &p.v, 0),
1014+ (3, 3) => (&p.h, stride, &p.v, 1),
1015+ (2, 1) => (&p.h, 0, &p.c, 0),
1016+ (2, 3) => (&p.h, stride, &p.c, 0),
1017+ (1, 2) => (&p.v, 0, &p.c, 0),
1018+ _ => (&p.v, 1, &p.c, 0), // (3, 2)
1019+ };
1020+ // Slice-length check so a short plane can never OOB (the `+1` slack in the
1021+ // bounds test above covers the shifted operand's reach geometrically; this
1022+ // makes it a hard guarantee at the slice level too).
1023+ if base + oa + (bh - 1) * stride + bw > pa.len() || base + ob + (bh - 1) * stride + bw > pb.len() {
1024+ return None;
1025+ }
1026+ Some((pa, base + oa, pb, base + ob, stride))
1027+}
1028+
1029+pub fn hpel_block(
1030+ p: &HpelPlanes,
1031+ x0: usize,
1032+ y0: usize,
1033+ bw: usize,
1034+ bh: usize,
1035+ mvx: i32,
1036+ mvy: i32,
1037+ out: &mut [u8],
1038+) -> bool {
1039+ let _g = crate::prof::scope(crate::prof::Stage::MeHpel);
1040+ let (ix0, iy0) = (x0 as isize + (mvx >> 2) as isize, y0 as isize + (mvy >> 2) as isize);
1041+ let (fx, fy) = (mvx & 3, mvy & 3);
1042+ if fx == 0 && fy == 0 {
1043+ return false; // the full-pel copy path is already optimal
1044+ }
1045+ // Padded coordinates. The `+1` slack covers the `m`/`s` neighbours.
1046+ let (px, py) = (ix0 + p.pad as isize, iy0 + p.pad as isize);
1047+ if px < 0 || py < 0 || px + bw as isize + 1 > p.pw as isize || py + bh as isize + 1 > p.ph as isize {
1048+ return false;
1049+ }
1050+ let stride = p.stride;
1051+ let base = py as usize * stride + px as usize;
1052+
1053+ let single = match (fx, fy) {
1054+ (2, 0) => Some(&p.h),
1055+ (0, 2) => Some(&p.v),
1056+ (2, 2) => Some(&p.c),
1057+ _ => None,
1058+ };
1059+ // Descent C: single-plane (half-pel) reads are CONTIGUOUS AT PLANE STRIDE — they
1060+ // could be SATD'd in place like the interior full-pel path instead of copied into
1061+ // a temp. Count the split before building that path.
1062+ #[cfg(feature = "profile")]
1063+ crate::inter::hpelphase::bump(if single.is_some() { 0 } else { 1 });
1064+ if let Some(src) = single {
1065+ for r in 0..bh {
1066+ out[r * bw..r * bw + bw].copy_from_slice(&src[base + r * stride..][..bw]);
1067+ }
1068+ return true;
1069+ }
1070+
1071+ // Quarter-pel: (a + b + 1) >> 1 of two planes. The operand table (the spec's
1072+ // `m`/`s` neighbour shifts) lives in ONE place — `hpel_qpel_refs` — so the
1073+ // materializing path here and the fused avg+SATD path can never drift apart.
1074+ let Some((pa, ba, pb, bb, qstride)) = hpel_qpel_refs(p, x0, y0, bw, bh, mvx, mvy) else {
1075+ return false;
1076+ };
1077+ match bw {
1078+ 16 => avg_rows::<16>(pa, ba, pb, bb, qstride, bh, out),
1079+ 8 => avg_rows::<8>(pa, ba, pb, bb, qstride, bh, out),
1080+ 4 => avg_rows::<4>(pa, ba, pb, bb, qstride, bh, out),
1081+ _ => return false,
1082+ }
1083+ true
1084+}
1085+
1086+#[inline]
1087+fn avg_rows<const BW: usize>(pa: &[u8], oa: usize, pb: &[u8], ob: usize, cw: usize, bh: usize, out: &mut [u8]) {
1088+ for r in 0..bh {
1089+ let sa = &pa[oa + r * cw..][..BW];
1090+ let sb = &pb[ob + r * cw..][..BW];
1091+ let o = &mut out[r * BW..r * BW + BW];
1092+ for i in 0..BW {
1093+ o[i] = ((sa[i] as u16 + sb[i] as u16 + 1) >> 1) as u8;
1094+ }
1095+ }
1096+}
1097+
1098+/// Quarter-pel motion compensation of a `bw`×`bh` luma block (`McLuma_c`).
1099+#[allow(clippy::too_many_arguments)]
1100+/// Descent E: accumulates one `mc_luma` call's cycles into its (size, phase) bucket.
1101+#[cfg(feature = "profile")]
1102+struct McCycleGuard {
1103+ b: usize,
1104+ t: u64,
1105+}
1106+#[cfg(feature = "profile")]
1107+impl Drop for McCycleGuard {
1108+ fn drop(&mut self) {
1109+ let c = crate::prof::tick().wrapping_sub(self.t);
1110+ mcstats::add_cycles(self.b, c);
1111+ mcstats::site_add(c);
1112+ }
1113+}
1114+
1115+pub fn mc_luma(
1116+ reference: &[u8],
1117+ cw: usize,
1118+ ch: usize,
1119+ x0: usize,
1120+ y0: usize,
1121+ bw: usize,
1122+ bh: usize,
1123+ mvx: i32,
1124+ mvy: i32,
1125+ out: &mut [u8],
1126+) {
1127+ let _g = crate::prof::scope(crate::prof::Stage::InterMc);
1128+ if abl_mc() {
1129+ out.fill(128);
1130+ return;
1131+ }
1132+ let (ix0, iy0) = (x0 as isize + (mvx >> 2) as isize, y0 as isize + (mvy >> 2) as isize);
1133+ let (fx, fy) = (mvx & 3, mvy & 3);
1134+ #[cfg(feature = "profile")]
1135+ mcstats::record(bw, bh, fx, fy);
1136+ // Descent E: time this call into its (size, phase) bucket. Guard drops at fn end.
1137+ #[cfg(feature = "profile")]
1138+ let _mcg = McCycleGuard { b: mcstats::bucket(bw, bh, fx, fy), t: crate::prof::tick() };
1139+ if fx == 0 && fy == 0 {
1140+ // Full-pel: a verbatim copy of the reference (`McCopy_c`). Interior → a
1141+ // row-wise slice copy (auto-vectorized); edge → per-pixel clamped.
1142+ if ix0 >= 0
1143+ && iy0 >= 0
1144+ && ix0 + bw as isize <= cw as isize
1145+ && iy0 + bh as isize <= ch as isize
1146+ && reference.len() >= cw * ch
1147+ {
1148+ let (rx, ry) = (ix0 as usize, iy0 as usize);
1149+ // Fixed-size fast path for the full 16×16 MB (the overwhelming common
1150+ // case). With `bw` a runtime parameter each `copy_from_slice(..bw)` is a
1151+ // variable-length `memcpy` CALL per row (~38 ns / MB); const-16 slices
1152+ // let LLVM emit inline 16-byte moves (~2 ns / MB). Byte-identical.
1153+ if bw == 16 && bh == 16 {
1154+ for dy in 0..16 {
1155+ let s = &reference[(ry + dy) * cw + rx..];
1156+ out[dy * 16..dy * 16 + 16].copy_from_slice(&s[..16]);
1157+ }
1158+ } else {
1159+ for dy in 0..bh {
1160+ out[dy * bw..dy * bw + bw]
1161+ .copy_from_slice(&reference[(ry + dy) * cw + rx..][..bw]);
1162+ }
1163+ }
1164+ } else {
1165+ for dy in 0..bh {
1166+ for dx in 0..bw {
1167+ out[dy * bw + dx] =
1168+ at(reference, cw, ch, ix0 + dx as isize, iy0 + dy as isize) as u8;
1169+ }
1170+ }
1171+ }
1172+ return;
1173+ }
1174+ // Sub-pel: extract the clamped tile once, then run the openh264 block kernels.
1175+ // Tile + half-pel staging live in per-thread scratch (see `McScratch`) so the
1176+ // ~1.4 KB of zero-fill and the tile's return-by-value copy are not repaid on
1177+ // every motion-search candidate. Destructuring gives `tile` and `a`/`b` as
1178+ // disjoint borrows of the same scratch.
1179+ MC_SCRATCH.with(|s| {
1180+ let McScratch { tile, a, b } = &mut *s.borrow_mut();
1181+ let ts = luma_tile_into(tile, reference, cw, ch, ix0, iy0, bw, bh);
1182+ mc_luma_subpel(tile, ts, bw, bh, fx, fy, a, b, out);
1183+ });
1184+}
1185+
1186+/// Eighth-pel bilinear motion compensation of a `bw`×`bh` chroma block (spec
1187+/// §8.4.2.2.2). The chroma motion vector equals the luma MV; for 4:2:0 it is
1188+/// interpreted at eighth-chroma-sample resolution.
1189+#[allow(clippy::too_many_arguments)]
1190+pub fn mc_chroma(
1191+ reference: &[u8],
1192+ cw: usize,
1193+ ch: usize,
1194+ x0: usize,
1195+ y0: usize,
1196+ bw: usize,
1197+ bh: usize,
1198+ mvx: i32,
1199+ mvy: i32,
1200+ out: &mut [u8],
1201+) {
1202+ let _g = crate::prof::scope(crate::prof::Stage::InterMc);
1203+ if abl_mc() {
1204+ out.fill(128);
1205+ return;
1206+ }
1207+ let (ix0, iy0) = (x0 as isize + (mvx >> 3) as isize, y0 as isize + (mvy >> 3) as isize);
1208+ let (fx, fy) = (mvx & 7, mvy & 7);
1209+ // Full-pel and fully inside the frame: `(64·a + 32) >> 6 == a`, a verbatim copy.
1210+ // Skip the per-pixel bilinear + 4× clamped `at()`; copy row-wise. Bit-identical.
1211+ if fx == 0
1212+ && fy == 0
1213+ && ix0 >= 0
1214+ && iy0 >= 0
1215+ && ix0 + bw as isize <= cw as isize
1216+ && iy0 + bh as isize <= ch as isize
1217+ && reference.len() >= cw * ch
1218+ {
1219+ let (rx, ry) = (ix0 as usize, iy0 as usize);
1220+ // Const-8 fast path for the full 8×8 chroma block (skip / P_16x16 common
1221+ // case): fixed-size slices → inline 8-byte moves, not a runtime-length
1222+ // `memcpy` call per row. Byte-identical. See the luma twin in `mc_luma`.
1223+ if bw == 8 && bh == 8 {
1224+ for dy in 0..8 {
1225+ let src = &reference[(ry + dy) * cw + rx..];
1226+ out[dy * 8..dy * 8 + 8].copy_from_slice(&src[..8]);
1227+ }
1228+ } else {
1229+ for dy in 0..bh {
1230+ let src = &reference[(ry + dy) * cw + rx..][..bw];
1231+ out[dy * bw..dy * bw + bw].copy_from_slice(src);
1232+ }
1233+ }
1234+ return;
1235+ }
1236+ // Sub-pel (and full-pel edge): extract the clamped (bw+1)×(bh+1) tile once —
1237+ // the edge-extended input `McChromaWithFragMv_c` reads — then the bilinear
1238+ // `A·p + B·p₊₁ + C·p₊ₛ + D·p₊ₛ₊₁` (`g_kuiABCD` weights), `(·+32)>>6`. A chroma
1239+ // block is at most 8×8 (half a 16×16 MB), so a 9×9 tile suffices. Bit-identical:
1240+ // the clamped tile reproduces `at()`, and full-pel weights give `(64·a+32)>>6==a`.
1241+ let ts = bw + 1;
1242+ let mut t = [0u8; 9 * 9];
1243+ // Interior fast path (see `luma_tile`): clamp-free contiguous row copies.
1244+ if ix0 >= 0
1245+ && iy0 >= 0
1246+ && ix0 + ts as isize <= cw as isize
1247+ && iy0 + (bh + 1) as isize <= ch as isize
1248+ && reference.len() >= cw * ch
1249+ {
1250+ let (rx0, ry0) = (ix0 as usize, iy0 as usize);
1251+ for ty in 0..bh + 1 {
1252+ let src = (ry0 + ty) * cw + rx0;
1253+ t[ty * ts..ty * ts + ts].copy_from_slice(&reference[src..src + ts]);
1254+ }
1255+ } else {
1256+ for ty in 0..bh + 1 {
1257+ let ry = (iy0 + ty as isize).clamp(0, ch as isize - 1) as usize * cw;
1258+ for tx in 0..ts {
1259+ let rx = (ix0 + tx as isize).clamp(0, cw as isize - 1) as usize;
1260+ t[ty * ts + tx] = reference.get(ry + rx).copied().unwrap_or(0);
1261+ }
1262+ }
1263+ }
1264+ let (wa, wb, wc, wd) = ((8 - fx) * (8 - fy), fx * (8 - fy), (8 - fx) * fy, fx * fy);
1265+ // 8-wide chroma (full-MB and 16×16-partition chroma — the common case) → the
1266+ // openh264 SSE2 bilinear over the same clamped tile. Width 2/4 stay scalar
1267+ // (width-4 is only an MMX kernel; width 2 has none). Bit-identical.
1268+ #[cfg(accel)]
1269+ if bw == 8 {
1270+ let abcd = [wa as u8, wb as u8, wc as u8, wd as u8];
1271+ rusty_h264_accel::mc_chroma_w8(&t, ts, out, bw, &abcd, bh);
1272+ return;
1273+ }
1274+ for r in 0..bh {
1275+ for c in 0..bw {
1276+ let p = r * ts + c;
1277+ let v = wa * t[p] as i32
1278+ + wb * t[p + 1] as i32
1279+ + wc * t[p + ts] as i32
1280+ + wd * t[p + ts + 1] as i32;
1281+ out[r * bw + c] = ((v + 32) >> 6) as u8;
1282+ }
1283+ }
1284+}
1285+
1286+// ---- Padded-reference MC (openh264 ExpandPicture style) ----
1287+//
1288+// A reference plane is stored with a replicated-edge border (`PAD_L` luma /
1289+// `PAD_C` chroma pixels), the picture origin at `(pad, pad)` and `stride` = the
1290+// padded width. MC then reads the frame DIRECTLY at the MV offset — no per-call
1291+// clamped tile — because reads into the border hit valid replicated pixels. For
1292+// the rare MV whose 6-tap halo would exceed the border, we fall back to the
1293+// clamped tile (reading the padded interior), which is bit-identical to the
1294+// exact-frame path.
1295+//
1296+// STATUS: implemented + bit-exact (the `mc_*_padded_matches_exact` tests + a full
1297+// decoder wiring verified 35/35 corpus MATCH), but measured **~0** vs the tile
1298+// path on x86-64 — once `luma_tile`'s interior fast path made extraction a
1299+// vectorized copy, the remaining win (skipping the copy) is offset by the
1300+// padded direct read's worse kernel cache locality (full-frame stride vs the
1301+// L1-resident tile) plus the per-frame expand/copy cost. Kept UNWIRED as a ready
1302+// option for a workload/target where tile extraction dominates (e.g. slower
1303+// memory, or hand-asm kernels tuned for the big-stride read). To wire: store
1304+// `RefFrame` planes padded (`expand_plane` in `as_reference`) and call these
1305+// instead of `mc_luma`/`mc_chroma`.
1306+
1307+/// Luma reference border width (covers full-pel MVs to ±30 px before fallback).
1308+pub const PAD_L: usize = 32;
1309+/// Chroma reference border width (= `PAD_L`/2, matching the half-rate chroma MV).
1310+pub const PAD_C: usize = 16;
1311+
1312+/// Fills the `pad`-wide replicated-edge border of a plane whose picture (`pw×ph`)
1313+/// sits at offset `(pad, pad)` with `stride`. Mirrors openh264 `ExpandPictureLuma_c`:
1314+/// left/right cols replicate the edge pixel; top/bottom rows replicate the (already
1315+/// edge-filled) first/last picture row, so the corners come out right.
1316+pub fn expand_plane(buf: &mut [u8], stride: usize, pad: usize, pw: usize, ph: usize) {
1317+ for y in 0..ph {
1318+ let row = (y + pad) * stride;
1319+ let (left, right) = (buf[row + pad], buf[row + pad + pw - 1]);
1320+ for x in 0..pad {
1321+ buf[row + x] = left;
1322+ buf[row + pad + pw + x] = right;
1323+ }
1324+ }
1325+ let first = pad * stride;
1326+ let last = (pad + ph - 1) * stride;
1327+ for y in 0..pad {
1328+ buf.copy_within(first..first + stride, y * stride);
1329+ buf.copy_within(last..last + stride, (pad + ph + y) * stride);
1330+ }
1331+}
1332+
1333+/// Quarter-pel luma MC reading a padded reference directly (no clamped tile when
1334+/// the halo is in-border). `x0,y0` are the block's picture coords; `stride`/`pad`
1335+/// describe the padded plane; `pw,ph` are the picture dims. Bit-identical to
1336+/// [`mc_luma`] on the equivalent exact frame.
1337+#[allow(clippy::too_many_arguments)]
1338+/// MEASUREMENT KNOB — `RFF_ABL_MC=1` makes both padded motion-compensation
1339+/// primitives return immediately with a flat block, pricing INTER PREDICTION by
1340+/// ablation on the UNINSTRUMENTED binary.
1341+///
1342+/// Placed inside the two primitives rather than at their ~13 decoder call sites so
1343+/// the ablation cannot miss one, and so every caller, every call COUNT and all the
1344+/// surrounding glue (partition walk, MV derivation, buffer setup) stay exactly as
1345+/// they were — what is priced is the interpolation work itself, nothing else.
1346+///
1347+/// Frame count is unaffected: parsing and residual decoding are untouched. Output
1348+/// pixels are wrong while this is set, by design — it is never a shipping path.
1349+/// Read once; the branch predicts perfectly.
1350+#[inline]
1351+pub(crate) fn abl_mc() -> bool {
1352+ use std::sync::atomic::{AtomicU8, Ordering};
1353+ static ON: AtomicU8 = AtomicU8::new(0);
1354+ match ON.load(Ordering::Relaxed) {
1355+ 1 => true,
1356+ 2 => false,
1357+ _ => {
1358+ let on = std::env::var_os("RFF_ABL_MC").is_some_and(|v| v != "0");
1359+ ON.store(if on { 1 } else { 2 }, Ordering::Relaxed);
1360+ on
1361+ }
1362+ }
1363+}
1364+
1365+pub fn mc_luma_padded(
1366+ padded: &[u8],
1367+ stride: usize,
1368+ pad: usize,
1369+ pw: usize,
1370+ ph: usize,
1371+ x0: usize,
1372+ y0: usize,
1373+ bw: usize,
1374+ bh: usize,
1375+ mvx: i32,
1376+ mvy: i32,
1377+ out: &mut [u8],
1378+) {
1379+ with_mc_scratch(|scr| mc_luma_padded_pre(scr, padded, stride, pad, pw, ph, x0, y0, bw, bh, mvx, mvy, out))
1380+}
1381+
1382+/// [`mc_luma_padded`] with the scratch pre-borrowed (see [`with_mc_scratch`]).
1383+#[allow(clippy::too_many_arguments)]
1384+pub fn mc_luma_padded_pre(
1385+ scr: &mut McScratch,
1386+ padded: &[u8],
1387+ stride: usize,
1388+ pad: usize,
1389+ pw: usize,
1390+ ph: usize,
1391+ x0: usize,
1392+ y0: usize,
1393+ bw: usize,
1394+ bh: usize,
1395+ mvx: i32,
1396+ mvy: i32,
1397+ out: &mut [u8],
1398+) {
1399+ let _g = crate::prof::scope(crate::prof::Stage::InterMc);
1400+ let (ix0, iy0) = (x0 as isize + (mvx >> 2) as isize, y0 as isize + (mvy >> 2) as isize);
1401+ let (fx, fy) = (mvx & 3, mvy & 3);
1402+ // Size x phase census for the DECODER's MC. The facility existed but was wired
1403+ // only into `mc_luma` (the encoder's), so the decoder's own distribution had
1404+ // never been measured -- and it is the one that decides which const-width fast
1405+ // paths are worth having.
1406+ #[cfg(feature = "profile")]
1407+ mcstats::record(bw, bh, fx, fy);
1408+ #[cfg(feature = "profile")]
1409+ let _mcg = McCycleGuard { b: mcstats::bucket(bw, bh, fx, fy), t: crate::prof::tick() };
1410+ let p = pad as isize;
1411+ let (lo_x, lo_y) = (ix0 - 2, iy0 - 2);
1412+ // Malformed-stream armor: a mutated stream can hand a reference whose plane
1413+ // no longer matches the caller's geometry (mid-stream SPS change). The fast
1414+ // paths index arithmetically, so they require the buffer to be intact; the
1415+ // fallback below reads checked. One compare on the hot path.
1416+ let intact = stride >= pw + 2 * pad && padded.len() >= stride * (ph + 2 * pad);
1417+ let in_range = intact
1418+ && lo_x >= -p
1419+ && lo_y >= -p
1420+ && lo_x + (bw + 5) as isize <= pw as isize + p
1421+ && lo_y + (bh + 5) as isize <= ph as isize + p;
1422+ if in_range {
1423+ if fx == 0 && fy == 0 {
1424+ // CONST-WIDTH row copies. With a runtime `bw` each row lowers to a
1425+ // variable-length `memcpy` CALL, and the census priced a 16x16 full-pel
1426+ // copy at 377 cycles -- ~10x what 256 bytes should cost. H.264 emits
1427+ // only these five widths.
1428+ macro_rules! rows {
1429+ ($n:expr) => {{
1430+ for dy in 0..bh {
1431+ let src = ((iy0 + dy as isize + p) as usize) * stride + (ix0 + p) as usize;
1432+ out[dy * $n..dy * $n + $n].copy_from_slice(&padded[src..src + $n]);
1433+ }
1434+ }};
1435+ }
1436+ match bw {
1437+ 16 => rows!(16),
1438+ 8 => rows!(8),
1439+ 4 => rows!(4),
1440+ _ => {
1441+ for dy in 0..bh {
1442+ let src = ((iy0 + dy as isize + p) as usize) * stride + (ix0 + p) as usize;
1443+ out[dy * bw..dy * bw + bw].copy_from_slice(&padded[src..src + bw]);
1444+ }
1445+ }
1446+ }
1447+ } else {
1448+ let halo = ((lo_y + p) as usize) * stride + (lo_x + p) as usize;
1449+ mc_luma_subpel(&padded[halo..], stride, bw, bh, fx, fy, &mut scr.a, &mut scr.b, out);
1450+ }
1451+ return;
1452+ }
1453+ // Extreme MV: clamp the halo to the real picture, read the padded interior.
1454+ let ts = bw + 5;
1455+ let mut t = [0u8; LUMA_TILE * LUMA_TILE];
1456+ for ty in 0..bh + 5 {
1457+ let py = (lo_y + ty as isize).clamp(0, ph as isize - 1) as usize;
1458+ let ry = (py + pad) * stride;
1459+ for tx in 0..ts {
1460+ let px = (lo_x + tx as isize).clamp(0, pw as isize - 1) as usize;
1461+ // Checked: on intact buffers this never misses; on malformed ones a
1462+ // grey sample beats a panic (no conformance duty on garbage input).
1463+ t[ty * ts + tx] = padded.get(ry + px + pad).copied().unwrap_or(128);
1464+ }
1465+ }
1466+ if fx == 0 && fy == 0 {
1467+ for dy in 0..bh {
1468+ let s = (dy + 2) * ts + 2;
1469+ out[dy * bw..dy * bw + bw].copy_from_slice(&t[s..s + bw]);
1470+ }
1471+ } else {
1472+ mc_luma_subpel(&t, ts, bw, bh, fx, fy, &mut scr.a, &mut scr.b, out);
1473+ }
1474+}
1475+
1476+/// Eighth-pel chroma MC reading a padded reference directly. Bit-identical to
1477+/// [`mc_chroma`] on the equivalent exact frame.
1478+#[allow(clippy::too_many_arguments)]
1479+pub fn mc_chroma_padded(
1480+ padded: &[u8],
1481+ stride: usize,
1482+ pad: usize,
1483+ pw: usize,
1484+ ph: usize,
1485+ x0: usize,
1486+ y0: usize,
1487+ bw: usize,
1488+ bh: usize,
1489+ mvx: i32,
1490+ mvy: i32,
1491+ out: &mut [u8],
1492+) {
1493+ let _g = crate::prof::scope(crate::prof::Stage::InterMc);
1494+ let (ix0, iy0) = (x0 as isize + (mvx >> 3) as isize, y0 as isize + (mvy >> 3) as isize);
1495+ let (fx, fy) = (mvx & 7, mvy & 7);
1496+ let p = pad as isize;
1497+ let intact = stride >= pw + 2 * pad && padded.len() >= stride * (ph + 2 * pad);
1498+ let in_range = intact
1499+ && ix0 >= -p
1500+ && iy0 >= -p
1501+ && ix0 + (bw + 1) as isize <= pw as isize + p
1502+ && iy0 + (bh + 1) as isize <= ph as isize + p;
1503+ let (wa, wb, wc, wd) = ((8 - fx) * (8 - fy), fx * (8 - fy), (8 - fx) * fy, fx * fy);
1504+ if in_range {
1505+ if fx == 0 && fy == 0 {
1506+ for dy in 0..bh {
1507+ let src = ((iy0 + dy as isize + p) as usize) * stride + (ix0 + p) as usize;
1508+ out[dy * bw..dy * bw + bw].copy_from_slice(&padded[src..src + bw]);
1509+ }
1510+ return;
1511+ }
1512+ let halo = ((iy0 + p) as usize) * stride + (ix0 + p) as usize;
1513+ #[cfg(accel)]
1514+ {
1515+ // H-38: BOTH widths now take asm. The 4-wide path was missing, so every
1516+ // 8×8 B-direct sub-block and sub-8×8 partition fell to the scalar
1517+ // bilinear below — chroma MC then cost as much as luma on half the
1518+ // pixels. Both kernels are pinned bit-identical to that scalar arm.
1519+ let abcd = [wa as u8, wb as u8, wc as u8, wd as u8];
1520+ if bw == 8 {
1521+ rusty_h264_accel::mc_chroma_w8(&padded[halo..], stride, out, bw, &abcd, bh);
1522+ return;
1523+ }
1524+ if bw == 4 {
1525+ rusty_h264_accel::mc_chroma_w4(&padded[halo..], stride, out, bw, &abcd, bh);
1526+ return;
1527+ }
1528+ }
1529+ for r in 0..bh {
1530+ for c in 0..bw {
1531+ let pp = halo + r * stride + c;
1532+ let v = wa * padded[pp] as i32
1533+ + wb * padded[pp + 1] as i32
1534+ + wc * padded[pp + stride] as i32
1535+ + wd * padded[pp + stride + 1] as i32;
1536+ out[r * bw + c] = ((v + 32) >> 6) as u8;
1537+ }
1538+ }
1539+ return;
1540+ }
1541+ // Extreme MV: clamp the (bw+1)² halo to the real picture, read the padded interior.
1542+ let ts = bw + 1;
1543+ let mut t = [0u8; 9 * 9];
1544+ for ty in 0..bh + 1 {
1545+ let py = (iy0 + ty as isize).clamp(0, ph as isize - 1) as usize;
1546+ let ry = (py + pad) * stride;
1547+ for tx in 0..ts {
1548+ let px = (ix0 + tx as isize).clamp(0, pw as isize - 1) as usize;
1549+ t[ty * ts + tx] = padded.get(ry + px + pad).copied().unwrap_or(128);
1550+ }
1551+ }
1552+ for r in 0..bh {
1553+ for c in 0..bw {
1554+ let pp = r * ts + c;
1555+ let v = wa * t[pp] as i32
1556+ + wb * t[pp + 1] as i32
1557+ + wc * t[pp + ts] as i32
1558+ + wd * t[pp + ts + 1] as i32;
1559+ out[r * bw + c] = ((v + 32) >> 6) as u8;
1560+ }
1561+ }
1562+}
1563+
1564+#[cfg(test)]
1565+mod tests {
1566+ use super::*;
1567+
1568+ fn rand_plane(pw: usize, ph: usize, seed: u32) -> Vec<u8> {
1569+ let mut s = seed;
1570+ (0..pw * ph)
1571+ .map(|_| {
1572+ s = s.wrapping_mul(1103515245).wrapping_add(12345);
1573+ (s >> 16) as u8
1574+ })
1575+ .collect()
1576+ }
1577+
1578+ fn make_padded(exact: &[u8], pw: usize, ph: usize, pad: usize) -> (Vec<u8>, usize) {
1579+ let stride = pw + 2 * pad;
1580+ let mut padded = vec![0u8; stride * (ph + 2 * pad)];
1581+ for y in 0..ph {
1582+ let d = (y + pad) * stride + pad;
1583+ padded[d..d + pw].copy_from_slice(&exact[y * pw..y * pw + pw]);
1584+ }
1585+ expand_plane(&mut padded, stride, pad, pw, ph);
1586+ (padded, stride)
1587+ }
1588+
1589+ #[test]
1590+ fn mc_luma_padded_matches_exact() {
1591+ let (pw, ph) = (48usize, 32usize);
1592+ let exact = rand_plane(pw, ph, 0x77);
1593+ let (padded, stride) = make_padded(&exact, pw, ph, PAD_L);
1594+ for &(bw, bh) in &[(16usize, 16usize), (8, 8), (16, 8), (8, 16), (4, 4)] {
1595+ for x0 in [0usize, 8, pw - bw] {
1596+ for y0 in [0usize, 8, ph - bh] {
1597+ for mvx in [-40i32, -20, -3, 0, 1, 2, 3, 7, 20, 40] {
1598+ for mvy in [-40i32, -20, -3, 0, 1, 2, 3, 7, 20, 40] {
1599+ let mut a = vec![0u8; bw * bh];
1600+ let mut b = vec![0u8; bw * bh];
1601+ mc_luma(&exact, pw, ph, x0, y0, bw, bh, mvx, mvy, &mut a);
1602+ mc_luma_padded(
1603+ &padded, stride, PAD_L, pw, ph, x0, y0, bw, bh, mvx, mvy, &mut b,
1604+ );
1605+ assert_eq!(a, b, "luma bw={bw} x0={x0} y0={y0} mv=({mvx},{mvy})");
1606+ }
1607+ }
1608+ }
1609+ }
1610+ }
1611+ }
1612+
1613+ #[test]
1614+ fn mc_chroma_padded_matches_exact() {
1615+ let (pw, ph) = (24usize, 16usize);
1616+ let exact = rand_plane(pw, ph, 0x99);
1617+ let (padded, stride) = make_padded(&exact, pw, ph, PAD_C);
1618+ for &(bw, bh) in &[(8usize, 8usize), (4, 4), (8, 4), (4, 8), (2, 2)] {
1619+ for x0 in [0usize, 4, pw - bw] {
1620+ for y0 in [0usize, 4, ph - bh] {
1621+ for mvx in [-40i32, -16, -3, 0, 1, 5, 8, 16, 40] {
1622+ for mvy in [-40i32, -16, -3, 0, 1, 5, 8, 16, 40] {
1623+ let mut a = vec![0u8; bw * bh];
1624+ let mut b = vec![0u8; bw * bh];
1625+ mc_chroma(&exact, pw, ph, x0, y0, bw, bh, mvx, mvy, &mut a);
1626+ mc_chroma_padded(
1627+ &padded, stride, PAD_C, pw, ph, x0, y0, bw, bh, mvx, mvy, &mut b,
1628+ );
1629+ assert_eq!(a, b, "chroma bw={bw} x0={x0} y0={y0} mv=({mvx},{mvy})");
1630+ }
1631+ }
1632+ }
1633+ }
1634+ }
1635+ }
1636+
1637+ /// Campaign-3 oracle: the fused single-pass builder must fill H/V/C
1638+ /// byte-for-byte like the tile-walk builder, across geometries whose padded
1639+ /// dimensions are and are not multiples of 16 (partial edge tiles) and with
1640+ /// enough randomness to exercise the clip.
1641+ #[test]
1642+ fn fused_hpel_builder_matches_tiles() {
1643+ let mut st = 0x5eed_f00d_dead_beefu64;
1644+ let mut lcg = move || {
1645+ st = st.wrapping_mul(6364136223846793005).wrapping_add(1442695040888963407);
1646+ (st >> 33) as u8
1647+ };
1648+ for &(cw, ch, pad) in &[(64usize, 48usize, 16usize), (80, 64, 12), (176, 144, 32)] {
1649+ let reference: Vec<u8> = (0..cw * ch).map(|_| lcg()).collect();
1650+ let (pw, ph) = (cw + 2 * pad, ch + 2 * pad);
1651+ // The same edge-replicated padded source `build_hpel_planes` constructs.
1652+ let mut f = vec![0u8; pw * ph];
1653+ for y in 0..ph {
1654+ let sy = (y as isize - pad as isize).clamp(0, ch as isize - 1) as usize;
1655+ let row = &reference[sy * cw..sy * cw + cw];
1656+ let d = &mut f[y * pw..y * pw + pw];
1657+ d[..pad].fill(row[0]);
1658+ d[pad..pad + cw].copy_from_slice(row);
1659+ d[pad + cw..].fill(row[cw - 1]);
1660+ }
1661+ let (mut h1, mut v1, mut c1) = (vec![0u8; pw * ph], vec![0u8; pw * ph], vec![0u8; pw * ph]);
1662+ let (mut h2, mut v2, mut c2) = (vec![0u8; pw * ph], vec![0u8; pw * ph], vec![0u8; pw * ph]);
1663+ build_hpel_tiles(&f, pw, ph, &mut h1, &mut v1, &mut c1);
1664+ build_hpel_fused(&f, pw, ph, &mut h2, &mut v2, &mut c2);
1665+ assert_eq!(h1, h2, "H plane differs at {cw}x{ch} pad {pad}");
1666+ assert_eq!(v1, v2, "V plane differs at {cw}x{ch} pad {pad}");
1667+ assert_eq!(c1, c2, "C plane differs at {cw}x{ch} pad {pad}");
1668+ // AVX2 fused kernel: byte-identical to the scalar fused builder (and
1669+ // transitively to the tiles) on every geometry, including widths whose
1670+ // vector interior leaves scalar tails.
1671+ #[cfg(accel)]
1672+ {
1673+ let (mut h3, mut v3, mut c3) =
1674+ (vec![0u8; pw * ph], vec![0u8; pw * ph], vec![0u8; pw * ph]);
1675+ if rusty_h264_accel::hpel_fused(&f, pw, ph, &mut h3, &mut v3, &mut c3) {
1676+ assert_eq!(h1, h3, "AVX2 H plane differs at {cw}x{ch} pad {pad}");
1677+ assert_eq!(v1, v3, "AVX2 V plane differs at {cw}x{ch} pad {pad}");
1678+ assert_eq!(c1, c3, "AVX2 C plane differs at {cw}x{ch} pad {pad}");
1679+ }
1680+ }
1681+ }
1682+ }
1683+
1684+ /// The plane cache must be BIT-IDENTICAL to `mc_luma` wherever it applies —
1685+ /// that identity is what keeps the motion search's decisions, and therefore the
1686+ /// bitstream, unchanged. Sweeps every sub-pel phase, every block size, and a
1687+ /// range of positions including ones near the frame edge (where it must decline).
1688+ #[test]
1689+ fn hpel_block_matches_mc_luma_exactly() {
1690+ let (cw, ch) = (96usize, 64usize);
1691+ let mut reference = vec![0u8; cw * ch];
1692+ let mut s: u32 = 0x9E37_79B9;
1693+ for p in reference.iter_mut() {
1694+ s = s.wrapping_mul(1_664_525).wrapping_add(1_013_904_223);
1695+ *p = (s >> 24) as u8;
1696+ }
1697+ let planes = build_hpel_planes(&reference, cw, ch);
1698+
1699+ let mut checked = 0;
1700+ for (bw, bh) in [(16, 16), (16, 8), (8, 16), (8, 8), (8, 4), (4, 8), (4, 4)] {
1701+ for fy in 0..4i32 {
1702+ for fx in 0..4i32 {
1703+ if fx == 0 && fy == 0 {
1704+ continue; // full-pel is the copy path, not the plane path
1705+ }
1706+ for y0 in (0..ch - bh).step_by(7) {
1707+ for x0 in (0..cw - bw).step_by(5) {
1708+ for &(dx, dy) in &[(0i32, 0i32), (4, 0), (0, 4), (-4, -4), (8, 8), (-64, -64), (96, 40), (-96, 60), (40, -96)] {
1709+ let (mvx, mvy) = (dx + fx, dy + fy);
1710+ let mut want = [0u8; 256];
1711+ mc_luma(&reference, cw, ch, x0, y0, bw, bh, mvx, mvy, &mut want);
1712+ let mut got = [0u8; 256];
1713+ if !hpel_block(&planes, x0, y0, bw, bh, mvx, mvy, &mut got) {
1714+ continue; // declined (edge) -> caller falls back
1715+ }
1716+ assert_eq!(
1717+ &got[..bw * bh],
1718+ &want[..bw * bh],
1719+ "bw={bw} bh={bh} fx={fx} fy={fy} x0={x0} y0={y0} mv=({mvx},{mvy})"
1720+ );
1721+ checked += 1;
1722+ }
1723+ }
1724+ }
1725+ }
1726+ }
1727+ }
1728+ assert!(checked > 5_000, "too few positions exercised: {checked}");
1729+ }
1730+
1731+ #[test]
1732+ fn mc_luma_block_kernels_match_per_pixel() {
1733+ // The block-kernel MC must be bit-identical to the per-pixel `luma_sample`
1734+ // reference for every quarter-pel position, across interior AND edge blocks
1735+ // (negative / off-frame MVs that exercise the clamped tile vs `at()`).
1736+ let (cw, ch) = (40usize, 32usize);
1737+ let mut state = 0x1357_9bdfu32;
1738+ let mut next = || {
1739+ state = state.wrapping_mul(1_664_525).wrapping_add(1_013_904_223);
1740+ (state >> 24) as u8
1741+ };
1742+ let reference: Vec<u8> = (0..cw * ch).map(|_| next()).collect();
1743+ for &(bw, bh) in &[(16, 16), (8, 8), (4, 4), (8, 16), (16, 8)] {
1744+ for &(x0, y0) in &[(8usize, 8usize), (0, 0), (cw - bw, ch - bh)] {
1745+ for mvx in -9..=9 {
1746+ for mvy in -9..=9 {
1747+ let mut got = vec![0u8; bw * bh];
1748+ mc_luma(&reference, cw, ch, x0, y0, bw, bh, mvx, mvy, &mut got);
1749+ let ix0 = x0 as isize + (mvx >> 2) as isize;
1750+ let iy0 = y0 as isize + (mvy >> 2) as isize;
1751+ let (fx, fy) = (mvx & 3, mvy & 3);
1752+ for dy in 0..bh {
1753+ for dx in 0..bw {
1754+ let want = luma_sample(
1755+ &reference, cw, ch,
1756+ ix0 + dx as isize, iy0 + dy as isize, fx, fy,
1757+ ) as u8;
1758+ assert_eq!(
1759+ got[dy * bw + dx], want,
1760+ "bw{bw}x{bh} at ({x0},{y0}) mv({mvx},{mvy}) px({dx},{dy})"
1761+ );
1762+ }
1763+ }
1764+ }
1765+ }
1766+ }
1767+ }
1768+ }
1769+
1770+ #[test]
1771+ fn mc_chroma_block_matches_per_pixel() {
1772+ let (cw, ch) = (24usize, 20usize);
1773+ let mut state = 0xabcd_1234u32;
1774+ let mut next = || {
1775+ state = state.wrapping_mul(1_664_525).wrapping_add(1_013_904_223);
1776+ (state >> 24) as u8
1777+ };
1778+ let reference: Vec<u8> = (0..cw * ch).map(|_| next()).collect();
1779+ let pp = |ix: isize, iy: isize, fx: i32, fy: i32| -> u8 {
1780+ let a = at(&reference, cw, ch, ix, iy);
1781+ let b = at(&reference, cw, ch, ix + 1, iy);
1782+ let c = at(&reference, cw, ch, ix, iy + 1);
1783+ let d = at(&reference, cw, ch, ix + 1, iy + 1);
1784+ (((8 - fx) * (8 - fy) * a + fx * (8 - fy) * b + (8 - fx) * fy * c + fx * fy * d + 32) >> 6)
1785+ as u8
1786+ };
1787+ for &(bw, bh) in &[(8, 8), (4, 4), (8, 4), (4, 8)] {
1788+ for &(x0, y0) in &[(4usize, 4usize), (0, 0), (cw - bw, ch - bh)] {
1789+ for mvx in -12..=12 {
1790+ for mvy in -12..=12 {
1791+ let mut got = vec![0u8; bw * bh];
1792+ mc_chroma(&reference, cw, ch, x0, y0, bw, bh, mvx, mvy, &mut got);
1793+ let ix0 = x0 as isize + (mvx >> 3) as isize;
1794+ let iy0 = y0 as isize + (mvy >> 3) as isize;
1795+ let (fx, fy) = (mvx & 7, mvy & 7);
1796+ for dy in 0..bh {
1797+ for dx in 0..bw {
1798+ assert_eq!(
1799+ got[dy * bw + dx],
1800+ pp(ix0 + dx as isize, iy0 + dy as isize, fx, fy),
1801+ "bw{bw}x{bh} at ({x0},{y0}) mv({mvx},{mvy}) px({dx},{dy})"
1802+ );
1803+ }
1804+ }
1805+ }
1806+ }
1807+ }
1808+ }
1809+ }
1810+
1811+ #[test]
1812+ fn median_of_three() {
1813+ assert_eq!(median3(1, 2, 3), 2);
1814+ assert_eq!(median3(3, 1, 2), 2);
1815+ assert_eq!(median3(-5, 0, 5), 0);
1816+ assert_eq!(median3(7, 7, 2), 7);
1817+ }
1818+
1819+ #[test]
1820+ fn mv_predict_single_neighbor_uses_it() {
1821+ let a = MvNeighbor { available: true, mv: (8, -4), ref_idx: 0 };
1822+ // B and C unavailable, A available → predictor is A.
1823+ assert_eq!(predict_mv(a, MvNeighbor::NONE, MvNeighbor::NONE, 0), (8, -4));
1824+ }
1825+
1826+ #[test]
1827+ fn mv_predict_median_when_all_inter() {
1828+ let a = MvNeighbor { available: true, mv: (4, 0), ref_idx: 0 };
1829+ let b = MvNeighbor { available: true, mv: (8, 0), ref_idx: 0 };
1830+ let c = MvNeighbor { available: true, mv: (12, 0), ref_idx: 0 };
1831+ assert_eq!(predict_mv(a, b, c, 0), (8, 0));
1832+ }
1833+
1834+ #[test]
1835+ fn mv_predict_one_matching_ref_wins() {
1836+ // Only B references ref 0; A and C are intra → predictor is B.
1837+ let a = MvNeighbor { available: true, mv: (0, 0), ref_idx: -1 };
1838+ let b = MvNeighbor { available: true, mv: (5, 7), ref_idx: 0 };
1839+ let c = MvNeighbor { available: true, mv: (0, 0), ref_idx: -1 };
1840+ assert_eq!(predict_mv(a, b, c, 0), (5, 7));
1841+ }
1842+
1843+ #[test]
1844+ fn mv_predict_distinguishes_refs() {
1845+ // A references ref 1, B references ref 0, C intra. For cur_ref 0 only B
1846+ // matches → B; for cur_ref 1 only A matches → A.
1847+ let a = MvNeighbor { available: true, mv: (4, 4), ref_idx: 1 };
1848+ let b = MvNeighbor { available: true, mv: (5, 7), ref_idx: 0 };
1849+ let c = MvNeighbor { available: true, mv: (0, 0), ref_idx: -1 };
1850+ assert_eq!(predict_mv(a, b, c, 0), (5, 7));
1851+ assert_eq!(predict_mv(a, b, c, 1), (4, 4));
1852+ }
1853+
1854+ #[test]
1855+ fn mc_luma_zero_mv_copies() {
1856+ let reference = vec![
1857+ 0, 1, 2, 3, 10, 11, 12, 13, 20, 21, 22, 23, 30, 31, 32, 33,
1858+ ];
1859+ let mut out = [0u8; 4];
1860+ mc_luma(&reference, 4, 4, 1, 1, 2, 2, 0, 0, &mut out);
1861+ assert_eq!(out, [11, 12, 21, 22]);
1862+ }
1863+
1864+ #[test]
1865+ fn mc_luma_clamps_at_edges() {
1866+ let reference = vec![5, 6, 7, 8];
1867+ let mut out = [0u8; 4];
1868+ mc_luma(&reference, 2, 2, 0, 0, 2, 2, -40, -40, &mut out);
1869+ assert_eq!(out, [5, 5, 5, 5]);
1870+ }
1871+
1872+ #[test]
1873+ fn mc_luma_halfpel_on_flat_is_flat() {
1874+ // A flat reference must interpolate to the same flat value at any frac.
1875+ let reference = vec![100u8; 8 * 8];
1876+ let mut out = [0u8; 16];
1877+ for &(fx, fy) in &[(2, 0), (0, 2), (2, 2), (1, 1), (3, 3)] {
1878+ mc_luma(&reference, 8, 8, 2, 2, 4, 4, fx, fy, &mut out);
1879+ assert!(out.iter().all(|&p| p == 100), "frac ({fx},{fy})");
1880+ }
1881+ }
1882+
1883+ #[test]
1884+ fn mc_chroma_zero_mv_copies() {
1885+ let reference = vec![0, 1, 2, 3, 10, 11, 12, 13, 20, 21, 22, 23, 30, 31, 32, 33];
1886+ let mut out = [0u8; 4];
1887+ mc_chroma(&reference, 4, 4, 1, 1, 2, 2, 0, 0, &mut out);
1888+ assert_eq!(out, [11, 12, 21, 22]);
1889+ }
1890+
1891+ #[test]
1892+ fn mc_chroma_bilinear_midpoint() {
1893+ // Horizontal ramp 0,8; chroma frac 4 (half) → midpoint 4.
1894+ let reference = vec![0u8, 8, 0, 8];
1895+ let mut out = [0u8; 1];
1896+ mc_chroma(&reference, 2, 2, 0, 0, 1, 1, 4, 0, &mut out);
1897+ assert_eq!(out[0], 4);
1898+ }
1899+}
vendor/rusty_h264-common/src/lib.rsadded+57 -0
@@ -0,0 +1,57 @@
1+//! Shared primitives for the `rusty_h264` pure-Rust H.264 codec.
2+//!
3+//! # Global allocator
4+//!
5+//! Upstream's `global-alloc` feature installed `rusty_alloc` as the process-wide
6+//! allocator here. This vendored copy does not (see the edith patch below the
7+//! crate attributes); the feature is kept declared but empty so the sibling
8+//! decoder/encoder manifests still resolve. The process uses the system
9+//! allocator.
10+//!
11+//! This crate is the foundation both the encoder and decoder sit on. It is
12+//! `#![forbid(unsafe_code)]`: the bit-twiddling core of an H.264 codec is
13+//! exactly where memory-safety bugs hide in the C implementations, so we keep
14+//! it provably safe.
15+//!
16+//! Modules mirror the concerns shared across `codec/common` in Cisco's
17+//! openh264:
18+//! - [`bit_writer`] / [`bit_reader`] — MSB-first bit packing + Exp-Golomb.
19+//! - [`nal`] — NAL units, Annex-B framing, RBSP emulation prevention.
20+//! - [`types`] — shared enums and the raw YUV frame container.
21+//!
22+//! The shipped build is `#![forbid(unsafe_code)]`. The `profile` feature (a
23+//! measurement-only dev build, never shipped) relaxes this to unlock the `rdtsc`
24+//! timer in [`prof`]; that is the *only* unsafe in the crate and only under `profile`.
25+#![cfg_attr(not(feature = "profile"), forbid(unsafe_code))]
26+
27+// --- edith patch: no process-wide allocator ---
28+// Upstream installed `rusty_alloc` as the whole application's
29+// `#[global_allocator]` here, under a feature its own decoder and encoder turn
30+// on by default. Under sustained seeking edith churns decode-worker threads,
31+// and that allocator faulted inside `span_from_segments` on a fresh thread's
32+// very first allocation. The codec is unchanged; only this declaration is gone,
33+// so the process keeps glibc's malloc.
34+
35+pub mod aligned;
36+pub mod bit_reader;
37+pub mod bit_writer;
38+pub mod cabac_tables;
39+pub mod cavlc;
40+pub mod deblock;
41+
42+/// Whether the vendored SIMD kernels are compiled in (`asm` feature on x86-64).
43+/// Exposed so benchmarks can state which path they measured — a harness that
44+/// silently falls back to the scalar twin reports numbers that look like a
45+/// regression in the fast path.
46+pub const ACCEL: bool = cfg!(accel);
47+pub mod inter;
48+pub mod nal;
49+pub mod predict;
50+pub mod prof;
51+pub mod transform;
52+pub mod types;
53+
54+pub use bit_reader::BitReader;
55+pub use bit_writer::BitWriter;
56+pub use nal::{NalUnit, NalUnitType};
57+pub use types::{ChromaFormat, Profile, YuvFrame};
vendor/rusty_h264-common/src/nal.rsadded+232 -0
@@ -0,0 +1,232 @@
1+//! NAL units, Annex-B framing, and RBSP emulation-prevention.
2+//!
3+//! H.264 carries syntax in NAL (Network Abstraction Layer) units. In the
4+//! Annex-B byte stream each NAL is prefixed by a start code (`00 00 01`, often
5+//! `00 00 00 01`). Within a NAL, the raw payload (RBSP) is escaped so the
6+//! start-code pattern can never appear by accident: any `00 00 00/01/02/03`
7+//! gets a `03` emulation-prevention byte inserted, producing the SODB/EBSP.
8+
9+/// NAL unit type (`nal_unit_type`, 5 bits). Only the subset relevant to a
10+/// Constrained Baseline encoder/decoder is named; others are `Other`.
11+#[derive(Debug, Clone, Copy, PartialEq, Eq)]
12+pub enum NalUnitType {
13+ /// Coded slice of a non-IDR picture.
14+ NonIdrSlice,
15+ /// Coded slice of an IDR picture.
16+ IdrSlice,
17+ /// Supplemental enhancement information.
18+ Sei,
19+ /// Sequence parameter set.
20+ Sps,
21+ /// Picture parameter set.
22+ Pps,
23+ /// Access unit delimiter.
24+ AccessUnitDelimiter,
25+ /// Any type not specifically handled.
26+ Other(u8),
27+}
28+
29+impl NalUnitType {
30+ /// Numeric `nal_unit_type` value.
31+ pub fn id(self) -> u8 {
32+ match self {
33+ NalUnitType::NonIdrSlice => 1,
34+ NalUnitType::IdrSlice => 5,
35+ NalUnitType::Sei => 6,
36+ NalUnitType::Sps => 7,
37+ NalUnitType::Pps => 8,
38+ NalUnitType::AccessUnitDelimiter => 9,
39+ NalUnitType::Other(v) => v & 0x1f,
40+ }
41+ }
42+
43+ /// Parses a `nal_unit_type` value.
44+ pub fn from_id(v: u8) -> Self {
45+ match v & 0x1f {
46+ 1 => NalUnitType::NonIdrSlice,
47+ 5 => NalUnitType::IdrSlice,
48+ 6 => NalUnitType::Sei,
49+ 7 => NalUnitType::Sps,
50+ 8 => NalUnitType::Pps,
51+ 9 => NalUnitType::AccessUnitDelimiter,
52+ other => NalUnitType::Other(other),
53+ }
54+ }
55+}
56+
57+/// A NAL unit: a header (type + `nal_ref_idc`) plus its raw RBSP payload.
58+#[derive(Debug, Clone)]
59+pub struct NalUnit {
60+ /// `nal_ref_idc` (0..=3): non-zero marks the NAL as referenceable.
61+ pub ref_idc: u8,
62+ /// NAL unit type.
63+ pub nal_type: NalUnitType,
64+ /// Raw byte sequence payload (un-escaped).
65+ pub rbsp: Vec<u8>,
66+}
67+
68+impl NalUnit {
69+ /// Builds a NAL unit.
70+ pub fn new(ref_idc: u8, nal_type: NalUnitType, rbsp: Vec<u8>) -> Self {
71+ Self {
72+ ref_idc,
73+ nal_type,
74+ rbsp,
75+ }
76+ }
77+
78+ /// The one-byte NAL header: `forbidden_zero_bit(0) | nal_ref_idc | nal_unit_type`.
79+ pub fn header_byte(&self) -> u8 {
80+ ((self.ref_idc & 0x3) << 5) | self.nal_type.id()
81+ }
82+
83+ /// Appends this NAL to `out` as an Annex-B unit: 4-byte start code, header
84+ /// byte, then the emulation-prevented payload.
85+ pub fn write_annex_b(&self, out: &mut Vec<u8>) {
86+ out.extend_from_slice(&[0x00, 0x00, 0x00, 0x01]);
87+ out.push(self.header_byte());
88+ emulation_prevent_into(&self.rbsp, out);
89+ }
90+
91+ /// Serializes a single NAL as a standalone Annex-B byte stream.
92+ pub fn to_annex_b(&self) -> Vec<u8> {
93+ let mut out = Vec::with_capacity(self.rbsp.len() + 8);
94+ self.write_annex_b(&mut out);
95+ out
96+ }
97+}
98+
99+/// Inserts emulation-prevention bytes, appending the EBSP to `out`.
100+///
101+/// Whenever the next byte would complete a `00 00 00`, `00 00 01`, `00 00 02`,
102+/// or `00 00 03` sequence, a `03` is inserted after the two zeros.
103+pub fn emulation_prevent_into(rbsp: &[u8], out: &mut Vec<u8>) {
104+ let mut zeros = 0usize;
105+ for &b in rbsp {
106+ if zeros >= 2 && b <= 0x03 {
107+ out.push(0x03);
108+ zeros = 0;
109+ }
110+ out.push(b);
111+ if b == 0 {
112+ zeros += 1;
113+ } else {
114+ zeros = 0;
115+ }
116+ }
117+}
118+
119+/// Removes emulation-prevention bytes from an EBSP payload, returning the RBSP.
120+pub fn emulation_unprevent(ebsp: &[u8]) -> Vec<u8> {
121+ let mut out = Vec::with_capacity(ebsp.len());
122+ let mut zeros = 0usize;
123+ let mut i = 0;
124+ while i < ebsp.len() {
125+ let b = ebsp[i];
126+ if zeros >= 2 && b == 0x03 && i + 1 < ebsp.len() && ebsp[i + 1] <= 0x03 {
127+ // Drop this emulation-prevention byte.
128+ zeros = 0;
129+ i += 1;
130+ continue;
131+ }
132+ out.push(b);
133+ if b == 0 {
134+ zeros += 1;
135+ } else {
136+ zeros = 0;
137+ }
138+ i += 1;
139+ }
140+ out
141+}
142+
143+/// Splits an Annex-B byte stream into raw NAL byte slices (header + EBSP),
144+/// stripping start codes. Does not parse headers or un-escape payloads.
145+pub fn split_annex_b(stream: &[u8]) -> Vec<&[u8]> {
146+ let mut nals = Vec::new();
147+ let mut starts = Vec::new();
148+ let mut i = 0;
149+ while i + 3 <= stream.len() {
150+ if stream[i] == 0 && stream[i + 1] == 0 && stream[i + 2] == 1 {
151+ starts.push(i + 3);
152+ i += 3;
153+ } else {
154+ i += 1;
155+ }
156+ }
157+ for (idx, &s) in starts.iter().enumerate() {
158+ // The NAL runs to just before the next start code (minus any trailing
159+ // zero bytes that belong to the next start code's prefix).
160+ let end = if idx + 1 < starts.len() {
161+ let next = starts[idx + 1] - 3;
162+ // Trim the trailing zero of a 4-byte (00 00 00 01) start code.
163+ if next > s && stream[next - 1] == 0 {
164+ next - 1
165+ } else {
166+ next
167+ }
168+ } else {
169+ stream.len()
170+ };
171+ if end > s {
172+ nals.push(&stream[s..end]);
173+ }
174+ }
175+ nals
176+}
177+
178+#[cfg(test)]
179+mod tests {
180+ use super::*;
181+
182+ #[test]
183+ fn header_byte_packs_fields() {
184+ let nal = NalUnit::new(3, NalUnitType::Sps, vec![]);
185+ // ref_idc=3 (11), type=7 (00111) => 0110_0111
186+ assert_eq!(nal.header_byte(), 0b0110_0111);
187+ }
188+
189+ #[test]
190+ fn emulation_prevention_inserts_03() {
191+ // Each inserted 0x03 resets the zero-run counter, so five zeros then a
192+ // 1 escapes twice: 00 00 [03] 00 00 [03] 00 01.
193+ let mut out = Vec::new();
194+ emulation_prevent_into(&[0, 0, 0, 0, 0, 1], &mut out);
195+ assert_eq!(out, vec![0, 0, 3, 0, 0, 3, 0, 1]);
196+ }
197+
198+ #[test]
199+ fn emulation_roundtrip() {
200+ let payloads: &[&[u8]] = &[
201+ &[0, 0, 0, 1],
202+ &[0, 0, 1, 2, 3],
203+ &[1, 2, 3, 4, 5],
204+ &[0, 0, 0, 0, 0, 0],
205+ &[0, 0, 3, 0, 0, 3],
206+ ];
207+ for p in payloads {
208+ let mut ebsp = Vec::new();
209+ emulation_prevent_into(p, &mut ebsp);
210+ assert_eq!(&emulation_unprevent(&ebsp), p, "roundtrip {p:?}");
211+ }
212+ }
213+
214+ #[test]
215+ fn annex_b_split_and_unescape() {
216+ let sps = NalUnit::new(3, NalUnitType::Sps, vec![0, 0, 1, 0x42]);
217+ let pps = NalUnit::new(3, NalUnitType::Pps, vec![0xAB, 0xCD]);
218+ let mut stream = Vec::new();
219+ sps.write_annex_b(&mut stream);
220+ pps.write_annex_b(&mut stream);
221+
222+ let nals = split_annex_b(&stream);
223+ assert_eq!(nals.len(), 2);
224+
225+ // First NAL: header byte then EBSP.
226+ assert_eq!(NalUnitType::from_id(nals[0][0]), NalUnitType::Sps);
227+ assert_eq!(emulation_unprevent(&nals[0][1..]), vec![0, 0, 1, 0x42]);
228+
229+ assert_eq!(NalUnitType::from_id(nals[1][0]), NalUnitType::Pps);
230+ assert_eq!(emulation_unprevent(&nals[1][1..]), vec![0xAB, 0xCD]);
231+ }
232+}
vendor/rusty_h264-common/src/predict.rsadded+907 -0
@@ -0,0 +1,907 @@
1+//! Intra prediction + shared block reconstruction for I_16x16 macroblocks.
2+//!
3+//! These routines are used identically by the encoder (to reconstruct each
4+//! macroblock so the next one can predict from it) and the decoder. Keeping
5+//! them in one place guarantees the two stay bit-for-bit in agreement, which is
6+//! what intra prediction requires.
7+
8+use crate::transform::inverse_core;
9+
10+/// 4×4 luma block scan order → (block-x, block-y) within a macroblock, in units
11+/// of 4 samples. This is the order luma residual blocks are coded and the order
12+/// neighbor `nnz` values are indexed by.
13+pub const LUMA_4X4_SCAN_XY: [(usize, usize); 16] = [
14+ (0, 0), (1, 0), (0, 1), (1, 1),
15+ (2, 0), (3, 0), (2, 1), (3, 1),
16+ (0, 2), (1, 2), (0, 3), (1, 3),
17+ (2, 2), (3, 2), (2, 3), (3, 3),
18+];
19+
20+/// Chroma 4×4 block scan order → (block-x, block-y) within the 8×8, in units of
21+/// 4 samples (simple raster for 4:2:0).
22+pub const CHROMA_4X4_SCAN_XY: [(usize, usize); 4] = [(0, 0), (1, 0), (0, 1), (1, 1)];
23+
24+/// Maps a luma QP to its chroma QP (with `chroma_qp_index_offset == 0`).
25+/// MEASUREMENT KNOBS — ablation switches for pricing stages the scope profiler cannot
26+/// read (its per-call rdtsc tax at ~20M calls exceeds the thing being measured).
27+///
28+/// `RFF_ABL_INTRA=1` makes every intra predictor return a flat block; `RFF_ABL_RECON=1`
29+/// makes reconstruction return the prediction unchanged (residual discarded). Both leave
30+/// PARSING and every call count untouched — what is priced is the pixel work alone, so
31+/// the frame count is unaffected and the work-parity check still holds. Output pixels
32+/// are wrong while either is set, by design; these are never a shipping path.
33+/// Read once; the branch predicts perfectly.
34+#[inline]
35+pub(crate) fn abl_intra() -> bool {
36+ use std::sync::atomic::{AtomicU8, Ordering};
37+ static ON: AtomicU8 = AtomicU8::new(0);
38+ match ON.load(Ordering::Relaxed) {
39+ 1 => true,
40+ 2 => false,
41+ _ => {
42+ let on = std::env::var_os("RFF_ABL_INTRA").is_some_and(|v| v != "0");
43+ ON.store(if on { 1 } else { 2 }, Ordering::Relaxed);
44+ on
45+ }
46+ }
47+}
48+
49+#[inline]
50+pub(crate) fn abl_recon() -> bool {
51+ use std::sync::atomic::{AtomicU8, Ordering};
52+ static ON: AtomicU8 = AtomicU8::new(0);
53+ match ON.load(Ordering::Relaxed) {
54+ 1 => true,
55+ 2 => false,
56+ _ => {
57+ let on = std::env::var_os("RFF_ABL_RECON").is_some_and(|v| v != "0");
58+ ON.store(if on { 1 } else { 2 }, Ordering::Relaxed);
59+ on
60+ }
61+ }
62+}
63+
64+pub fn chroma_qp(qp: u8) -> u8 {
65+
66+ const QPC: [u8; 22] = [
67+ 29, 30, 31, 32, 32, 33, 34, 34, 35, 35, 36, 36, 37, 37, 37, 38, 38, 38, 39, 39, 39, 39,
68+ ];
69+ if qp < 30 {
70+ qp
71+ } else {
72+ QPC[(qp - 30) as usize]
73+ }
74+}
75+
76+/// CAVLC `nC` context from the left (`a`) and top (`b`) neighbor block `nnz`
77+/// counts (`None` = neighbor unavailable).
78+pub fn nc_from_neighbors(a: Option<u8>, b: Option<u8>) -> i32 {
79+ match (a, b) {
80+ (Some(na), Some(nb)) => (na as i32 + nb as i32 + 1) >> 1,
81+ (Some(na), None) => na as i32,
82+ (None, Some(nb)) => nb as i32,
83+ (None, None) => 0,
84+ }
85+}
86+
87+fn sum(s: &[u8]) -> i32 {
88+ s.iter().map(|&x| x as i32).sum()
89+}
90+
91+/// Intra_16x16 DC luma prediction: a single value used for all 256 samples.
92+pub fn luma16x16_dc(avail_top: bool, avail_left: bool, top: &[u8; 16], left: &[u8; 16]) -> u8 {
93+ let v = if avail_top && avail_left {
94+ (sum(top) + sum(left) + 16) >> 5
95+ } else if avail_top {
96+ (sum(top) + 8) >> 4
97+ } else if avail_left {
98+ (sum(left) + 8) >> 4
99+ } else {
100+ 128
101+ };
102+ v as u8
103+}
104+
105+/// The four `Intra_16x16` prediction modes (spec §8.3.3). The discriminant is
106+/// the `intra16x16_pred_mode` value carried in `mb_type`.
107+#[derive(Debug, Clone, Copy, PartialEq, Eq)]
108+pub enum I16Mode {
109+ Vertical = 0,
110+ Horizontal = 1,
111+ Dc = 2,
112+ Plane = 3,
113+}
114+
115+impl I16Mode {
116+ /// Parses a mode number (0..=3).
117+ pub fn from_id(v: u32) -> Self {
118+ match v & 3 {
119+ 0 => I16Mode::Vertical,
120+ 1 => I16Mode::Horizontal,
121+ 2 => I16Mode::Dc,
122+ _ => I16Mode::Plane,
123+ }
124+ }
125+
126+ /// Whether this mode is usable given neighbor availability.
127+ pub fn available(self, avail_top: bool, avail_left: bool) -> bool {
128+ match self {
129+ I16Mode::Vertical => avail_top,
130+ I16Mode::Horizontal => avail_left,
131+ I16Mode::Dc => true,
132+ I16Mode::Plane => avail_top && avail_left,
133+ }
134+ }
135+}
136+
137+/// Computes the 16×16 luma prediction for an `Intra_16x16` macroblock, returning
138+/// 256 raster samples. `corner` is the above-left neighbor (used by Plane).
139+pub fn luma16x16_pred(
140+ mode: I16Mode,
141+ avail_top: bool,
142+ avail_left: bool,
143+ top: &[u8; 16],
144+ left: &[u8; 16],
145+ corner: u8,
146+) -> [u8; 256] {
147+ if abl_intra() {
148+ return [128; 256];
149+ }
150+ let _g = crate::prof::scope(crate::prof::Stage::IntraPred);
151+ let mut out = [0u8; 256];
152+ match mode {
153+ I16Mode::Vertical => {
154+ for y in 0..16 {
155+ for x in 0..16 {
156+ out[y * 16 + x] = top[x];
157+ }
158+ }
159+ }
160+ I16Mode::Horizontal => {
161+ for y in 0..16 {
162+ for x in 0..16 {
163+ out[y * 16 + x] = left[y];
164+ }
165+ }
166+ }
167+ I16Mode::Dc => {
168+ let v = luma16x16_dc(avail_top, avail_left, top, left);
169+ out.fill(v);
170+ }
171+ I16Mode::Plane => {
172+ // p[x,-1] = top[x] (x 0..15), p[-1,y] = left[y], p[-1,-1] = corner.
173+ let tp = |i: isize| -> i32 {
174+ if i < 0 {
175+ corner as i32
176+ } else {
177+ top[i as usize] as i32
178+ }
179+ };
180+ let lf = |i: isize| -> i32 {
181+ if i < 0 {
182+ corner as i32
183+ } else {
184+ left[i as usize] as i32
185+ }
186+ };
187+ let mut h = 0i32;
188+ let mut v = 0i32;
189+ for xp in 0..8i32 {
190+ h += (xp + 1) * (tp(8 + xp as isize) - tp(6 - xp as isize));
191+ }
192+ for yp in 0..8i32 {
193+ v += (yp + 1) * (lf(8 + yp as isize) - lf(6 - yp as isize));
194+ }
195+ let a = 16 * (left[15] as i32 + top[15] as i32);
196+ let b = (5 * h + 32) >> 6;
197+ let c = (5 * v + 32) >> 6;
198+ for y in 0..16i32 {
199+ for x in 0..16i32 {
200+ let val = (a + b * (x - 7) + c * (y - 7) + 16) >> 5;
201+ out[(y * 16 + x) as usize] = clip_u8(val);
202+ }
203+ }
204+ }
205+ }
206+ out
207+}
208+
209+/// Intra 4×4 luma prediction (spec §8.3.1.2), all 9 modes. Returns 16 raster
210+/// samples. Neighbors: `top[0..4]` above, `top[4..8]` above-right (the caller
211+/// substitutes `top[3]` when the above-right block is unavailable), `left[0..4]`
212+/// to the left, `corner` above-left. `avail_top`/`avail_left` gate DC only;
213+/// callers must not select a mode whose neighbors are unavailable.
214+pub fn intra4x4_pred(
215+ mode: u8,
216+ avail_top: bool,
217+ avail_left: bool,
218+ top: &[u8; 8],
219+ left: &[u8; 4],
220+ corner: u8,
221+) -> [u8; 16] {
222+ if abl_intra() {
223+ return [128; 16];
224+ }
225+ let _g = crate::prof::scope(crate::prof::Stage::IntraPred);
226+ let t = |i: usize| top[i] as i32;
227+ let l = |i: usize| left[i] as i32;
228+ let c = corner as i32;
229+ // Top/left indexed with -1 → corner.
230+ let tt = |k: i32| -> i32 {
231+ if k < 0 {
232+ c
233+ } else {
234+ top[k as usize] as i32
235+ }
236+ };
237+ let ll = |k: i32| -> i32 {
238+ if k < 0 {
239+ c
240+ } else {
241+ left[k as usize] as i32
242+ }
243+ };
244+
245+ let mut p = [0i32; 16];
246+ match mode {
247+ 0 => {
248+ for y in 0..4 {
249+ for x in 0..4 {
250+ p[y * 4 + x] = t(x);
251+ }
252+ }
253+ }
254+ 1 => {
255+ for y in 0..4 {
256+ for x in 0..4 {
257+ p[y * 4 + x] = l(y);
258+ }
259+ }
260+ }
261+ 2 => {
262+ let v = if avail_top && avail_left {
263+ (t(0) + t(1) + t(2) + t(3) + l(0) + l(1) + l(2) + l(3) + 4) >> 3
264+ } else if avail_top {
265+ (t(0) + t(1) + t(2) + t(3) + 2) >> 2
266+ } else if avail_left {
267+ (l(0) + l(1) + l(2) + l(3) + 2) >> 2
268+ } else {
269+ 128
270+ };
271+ p.fill(v);
272+ }
273+ 3 => {
274+ // Diagonal down-left
275+ for y in 0..4 {
276+ for x in 0..4 {
277+ p[y * 4 + x] = if x == 3 && y == 3 {
278+ (t(6) + 3 * t(7) + 2) >> 2
279+ } else {
280+ let k = x + y;
281+ (t(k) + 2 * t(k + 1) + t(k + 2) + 2) >> 2
282+ };
283+ }
284+ }
285+ }
286+ 4 => {
287+ // Diagonal down-right
288+ for y in 0..4i32 {
289+ for x in 0..4i32 {
290+ p[(y * 4 + x) as usize] = if x > y {
291+ (tt(x - y - 2) + 2 * tt(x - y - 1) + tt(x - y) + 2) >> 2
292+ } else if x < y {
293+ (ll(y - x - 2) + 2 * ll(y - x - 1) + ll(y - x) + 2) >> 2
294+ } else {
295+ (t(0) + 2 * c + l(0) + 2) >> 2
296+ };
297+ }
298+ }
299+ }
300+ 5 => {
301+ // Vertical-right
302+ for y in 0..4i32 {
303+ for x in 0..4i32 {
304+ let zvr = 2 * x - y;
305+ let k = x - (y >> 1);
306+ p[(y * 4 + x) as usize] = if zvr >= 0 && zvr % 2 == 0 {
307+ (tt(k - 1) + tt(k) + 1) >> 1
308+ } else if zvr >= 0 {
309+ (tt(k - 2) + 2 * tt(k - 1) + tt(k) + 2) >> 2
310+ } else if zvr == -1 {
311+ (l(0) + 2 * c + t(0) + 2) >> 2
312+ } else {
313+ (ll(y - 1) + 2 * ll(y - 2) + ll(y - 3) + 2) >> 2
314+ };
315+ }
316+ }
317+ }
318+ 6 => {
319+ // Horizontal-down
320+ for y in 0..4i32 {
321+ for x in 0..4i32 {
322+ let zhd = 2 * y - x;
323+ let k = y - (x >> 1);
324+ p[(y * 4 + x) as usize] = if zhd >= 0 && zhd % 2 == 0 {
325+ (ll(k - 1) + ll(k) + 1) >> 1
326+ } else if zhd >= 0 {
327+ (ll(k - 2) + 2 * ll(k - 1) + ll(k) + 2) >> 2
328+ } else if zhd == -1 {
329+ (l(0) + 2 * c + t(0) + 2) >> 2
330+ } else {
331+ (tt(x - 1) + 2 * tt(x - 2) + tt(x - 3) + 2) >> 2
332+ };
333+ }
334+ }
335+ }
336+ 7 => {
337+ // Vertical-left
338+ for y in 0..4 {
339+ for x in 0..4 {
340+ let k = x + (y >> 1);
341+ p[y * 4 + x] = if y % 2 == 0 {
342+ (t(k) + t(k + 1) + 1) >> 1
343+ } else {
344+ (t(k) + 2 * t(k + 1) + t(k + 2) + 2) >> 2
345+ };
346+ }
347+ }
348+ }
349+ _ => {
350+ // Horizontal-up (mode 8)
351+ for y in 0..4 {
352+ for x in 0..4 {
353+ let zhu = x + 2 * y;
354+ let k = y + (x >> 1);
355+ p[y * 4 + x] = if zhu <= 4 && zhu % 2 == 0 {
356+ (l(k) + l(k + 1) + 1) >> 1
357+ } else if zhu < 5 {
358+ (l(k) + 2 * l(k + 1) + l(k + 2) + 2) >> 2
359+ } else if zhu == 5 {
360+ (l(2) + 3 * l(3) + 2) >> 2
361+ } else {
362+ l(3)
363+ };
364+ }
365+ }
366+ }
367+ }
368+ let mut out = [0u8; 16];
369+ for i in 0..16 {
370+ out[i] = clip_u8(p[i]);
371+ }
372+ out
373+}
374+
375+/// Intra chroma 8×8 DC prediction (spec §8.3.4): the 8×8 is split into four 4×4
376+/// regions, each predicted from its available neighbor run. Returns the 64
377+/// predicted samples in raster order. `top`/`left` are the 8 neighbor samples.
378+pub fn chroma8x8_dc(avail_top: bool, avail_left: bool, top: &[u8; 8], left: &[u8; 8]) -> [u8; 64] {
379+ let mut out = [128u8; 64];
380+ for &(bx, by) in &CHROMA_4X4_SCAN_XY {
381+ let (x0, y0) = (bx * 4, by * 4);
382+ let top4 = &top[x0..x0 + 4];
383+ let left4 = &left[y0..y0 + 4];
384+ // Which neighbor each region prefers (spec §8.3.4.1).
385+ let prefer_top = (x0, y0) == (4, 0);
386+ let prefer_left = (x0, y0) == (0, 4);
387+ let dc: i32 = if prefer_top {
388+ if avail_top {
389+ (sum(top4) + 2) >> 2
390+ } else if avail_left {
391+ (sum(left4) + 2) >> 2
392+ } else {
393+ 128
394+ }
395+ } else if prefer_left {
396+ if avail_left {
397+ (sum(left4) + 2) >> 2
398+ } else if avail_top {
399+ (sum(top4) + 2) >> 2
400+ } else {
401+ 128
402+ }
403+ } else {
404+ // (0,0) and (4,4): use both when available.
405+ if avail_top && avail_left {
406+ (sum(top4) + sum(left4) + 4) >> 3
407+ } else if avail_top {
408+ (sum(top4) + 2) >> 2
409+ } else if avail_left {
410+ (sum(left4) + 2) >> 2
411+ } else {
412+ 128
413+ }
414+ };
415+ for dy in 0..4 {
416+ for dx in 0..4 {
417+ out[(y0 + dy) * 8 + (x0 + dx)] = dc as u8;
418+ }
419+ }
420+ }
421+ out
422+}
423+
424+/// Intra chroma 8×8 prediction (spec §8.3.4), all four modes. `mode`:
425+/// 0 = DC, 1 = Horizontal, 2 = Vertical, 3 = Plane. `top`/`left` are the 8
426+/// neighbor samples; `corner` is the above-left (Plane only).
427+pub fn chroma8x8_pred(
428+ mode: u8,
429+ avail_top: bool,
430+ avail_left: bool,
431+ top: &[u8; 8],
432+ left: &[u8; 8],
433+ corner: u8,
434+) -> [u8; 64] {
435+ if abl_intra() {
436+ return [128; 64];
437+ }
438+ let _g = crate::prof::scope(crate::prof::Stage::IntraPred);
439+ match mode {
440+ 1 => {
441+ // Horizontal
442+ let mut out = [0u8; 64];
443+ for y in 0..8 {
444+ for x in 0..8 {
445+ out[y * 8 + x] = left[y];
446+ }
447+ }
448+ out
449+ }
450+ 2 => {
451+ // Vertical
452+ let mut out = [0u8; 64];
453+ for y in 0..8 {
454+ for x in 0..8 {
455+ out[y * 8 + x] = top[x];
456+ }
457+ }
458+ out
459+ }
460+ 3 => {
461+ // Plane
462+ let tt = |k: i32| if k < 0 { corner as i32 } else { top[k as usize] as i32 };
463+ let ll = |k: i32| if k < 0 { corner as i32 } else { left[k as usize] as i32 };
464+ let mut h = 0i32;
465+ let mut v = 0i32;
466+ for xp in 0..4i32 {
467+ h += (xp + 1) * (top[(4 + xp) as usize] as i32 - tt(2 - xp));
468+ }
469+ for yp in 0..4i32 {
470+ v += (yp + 1) * (left[(4 + yp) as usize] as i32 - ll(2 - yp));
471+ }
472+ let a = 16 * (left[7] as i32 + top[7] as i32);
473+ let b = (17 * h + 16) >> 5;
474+ let c = (17 * v + 16) >> 5;
475+ let mut out = [0u8; 64];
476+ for y in 0..8i32 {
477+ for x in 0..8i32 {
478+ out[(y * 8 + x) as usize] = clip_u8((a + b * (x - 3) + c * (y - 3) + 16) >> 5);
479+ }
480+ }
481+ out
482+ }
483+ _ => chroma8x8_dc(avail_top, avail_left, top, left),
484+ }
485+}
486+
487+/// Whether a chroma prediction mode is usable given neighbor availability.
488+pub fn chroma_mode_available(mode: u8, avail_top: bool, avail_left: bool) -> bool {
489+ match mode {
490+ 0 => true, // DC
491+ 1 => avail_left, // Horizontal
492+ 2 => avail_top, // Vertical
493+ _ => avail_top && avail_left, // Plane
494+ }
495+}
496+
497+/// Clips a value to the 8-bit pixel range.
498+#[inline]
499+pub fn clip_u8(v: i32) -> u8 {
500+ v.clamp(0, 255) as u8
501+}
502+
503+/// Reconstructs a 4×4 block: inverse-transform the dequantized coefficients and
504+/// add the prediction, clipping to 8-bit. `dequant` and `pred` are raster 4×4.
505+pub fn reconstruct_4x4(dequant: &[i32; 16], pred: &[i32; 16]) -> [u8; 16] {
506+ if abl_recon() {
507+ return std::array::from_fn(|i| clip_u8(pred[i]));
508+ }
509+ let _g = crate::prof::scope(crate::prof::Stage::Reconstruct);
510+ add_residual_4x4(&inverse_core(dequant), pred)
511+}
512+
513+/// Reconstructs a 4×4 block DIRECTLY into the frame plane: IDCT + add + clip +
514+/// store in one pass, with the prediction read strided from its buffer. Kills
515+/// the per-block `predb` i32 gather, the `[u8; 16]` result array, and the
516+/// separate `store` call — the resid-add boundary the WHYS Part 8/9 descent
517+/// priced. Honors the same ablation knob as `reconstruct_4x4`.
518+#[inline]
519+pub fn reconstruct_4x4_into(
520+ deq: &[i32; 16],
521+ pred: &[u8],
522+ p_off: usize,
523+ p_stride: usize,
524+ rec: &mut [u8],
525+ r_off: usize,
526+ r_stride: usize,
527+) {
528+ if abl_recon() {
529+ for r in 0..4 {
530+ for c in 0..4 {
531+ rec[r_off + r * r_stride + c] = pred[p_off + r * p_stride + c];
532+ }
533+ }
534+ return;
535+ }
536+ let _g = crate::prof::scope(crate::prof::Stage::Reconstruct);
537+ let res = crate::transform::inverse_core(deq);
538+ for r in 0..4 {
539+ for c in 0..4 {
540+ rec[r_off + r * r_stride + c] =
541+ clip_u8(pred[p_off + r * p_stride + c] as i32 + res[r * 4 + c]);
542+ }
543+ }
544+}
545+
546+/// Flat-residual twin of [`reconstruct_4x4_into`] (the DC-only fast path).
547+#[inline]
548+pub fn reconstruct_4x4_dc_into(
549+ rval: i32,
550+ pred: &[u8],
551+ p_off: usize,
552+ p_stride: usize,
553+ rec: &mut [u8],
554+ r_off: usize,
555+ r_stride: usize,
556+) {
557+ if abl_recon() {
558+ for r in 0..4 {
559+ for c in 0..4 {
560+ rec[r_off + r * r_stride + c] = pred[p_off + r * p_stride + c];
561+ }
562+ }
563+ return;
564+ }
565+ let _g = crate::prof::scope(crate::prof::Stage::Reconstruct);
566+ for r in 0..4 {
567+ for c in 0..4 {
568+ rec[r_off + r * r_stride + c] =
569+ clip_u8(pred[p_off + r * p_stride + c] as i32 + rval);
570+ }
571+ }
572+}
573+
574+/// Reconstructs a block whose residual is FLAT (every position carries the same
575+/// value `r`) — the tail of the DC-only fast path. Honors the same ablation
576+/// knob and profiling stage as [`reconstruct_4x4`] so measurement arms stay
577+/// comparable whichever path a block takes.
578+#[inline]
579+pub fn reconstruct_4x4_dc(r: i32, pred: &[i32; 16]) -> [u8; 16] {
580+ if abl_recon() {
581+ return std::array::from_fn(|i| clip_u8(pred[i]));
582+ }
583+ let _g = crate::prof::scope(crate::prof::Stage::Reconstruct);
584+ std::array::from_fn(|i| clip_u8(pred[i] + r))
585+}
586+
587+/// Adds an already-inverse-transformed residual block to its prediction and clips
588+/// to `u8`. Split out of [`reconstruct_4x4`] so callers that batch the inverse DCT
589+/// ([`crate::transform::inverse_dct_blocks`]) can share the add+clip tail.
590+#[inline]
591+pub fn add_residual_4x4(res: &[i32; 16], pred: &[i32; 16]) -> [u8; 16] {
592+ let mut out = [0u8; 16];
593+ for i in 0..16 {
594+ out[i] = clip_u8(pred[i] + res[i]);
595+ }
596+ out
597+}
598+
599+/// Intra_8x8 luma prediction (spec §8.3.2.2), all nine modes. Reference samples
600+/// are first low-pass filtered (§8.3.2.2.1) then the per-mode formulas — which
601+/// mirror the 4×4 ones over the 8-wide block — are applied. `top` holds the 16
602+/// samples p[0..15,-1] (8..15 substituted by the caller when no top-right),
603+/// `left` the 8 samples p[-1,0..7], `corner` is p[-1,-1]; `avail_corner` is the
604+/// above-left neighbor's availability. Returns 64 predicted samples (raster).
605+#[allow(clippy::needless_range_loop)] // filter loops read neighbors p[k-1..k+1]
606+pub fn intra8x8_pred(
607+ mode: u8,
608+ avail_top: bool,
609+ avail_left: bool,
610+ avail_corner: bool,
611+ top: &[u8; 16],
612+ left: &[u8; 8],
613+ corner: u8,
614+) -> [u8; 64] {
615+ let _g = crate::prof::scope(crate::prof::Stage::IntraPred);
616+ // ---- reference sample filtering (§8.3.2.2.1) ----
617+ let t = |k: usize| top[k] as i32;
618+ let l = |k: usize| left[k] as i32;
619+ let cc = corner as i32;
620+ let mut ft = [0i32; 16];
621+ ft[0] = if avail_corner {
622+ (cc + 2 * t(0) + t(1) + 2) >> 2
623+ } else {
624+ (3 * t(0) + t(1) + 2) >> 2
625+ };
626+ for k in 1..15 {
627+ ft[k] = (t(k - 1) + 2 * t(k) + t(k + 1) + 2) >> 2;
628+ }
629+ ft[15] = (t(14) + 3 * t(15) + 2) >> 2;
630+ let mut fl = [0i32; 8];
631+ fl[0] = if avail_corner {
632+ (cc + 2 * l(0) + l(1) + 2) >> 2
633+ } else {
634+ (3 * l(0) + l(1) + 2) >> 2
635+ };
636+ for k in 1..7 {
637+ fl[k] = (l(k - 1) + 2 * l(k) + l(k + 1) + 2) >> 2;
638+ }
639+ fl[7] = (l(6) + 3 * l(7) + 2) >> 2;
640+ let fc = if avail_corner {
641+ if avail_top && avail_left {
642+ (t(0) + 2 * cc + l(0) + 2) >> 2
643+ } else if avail_top {
644+ (3 * cc + t(0) + 2) >> 2
645+ } else if avail_left {
646+ (3 * cc + l(0) + 2) >> 2
647+ } else {
648+ cc
649+ }
650+ } else {
651+ cc
652+ };
653+ // Indexers with -1 → filtered corner (for the diagonal modes).
654+ let ttf = |k: i32| -> i32 {
655+ if k < 0 {
656+ fc
657+ } else {
658+ ft[k as usize]
659+ }
660+ };
661+ let llf = |k: i32| -> i32 {
662+ if k < 0 {
663+ fc
664+ } else {
665+ fl[k as usize]
666+ }
667+ };
668+
669+ let mut p = [0i32; 64];
670+ match mode {
671+ 0 => {
672+ for y in 0..8 {
673+ for x in 0..8 {
674+ p[y * 8 + x] = ft[x];
675+ }
676+ }
677+ }
678+ 1 => {
679+ for y in 0..8 {
680+ for x in 0..8 {
681+ p[y * 8 + x] = fl[y];
682+ }
683+ }
684+ }
685+ 2 => {
686+ let st: i32 = ft[0..8].iter().sum();
687+ let sl: i32 = fl[0..8].iter().sum();
688+ let v = if avail_top && avail_left {
689+ (st + sl + 8) >> 4
690+ } else if avail_top {
691+ (st + 4) >> 3
692+ } else if avail_left {
693+ (sl + 4) >> 3
694+ } else {
695+ 128
696+ };
697+ p.fill(v);
698+ }
699+ 3 => {
700+ for y in 0..8 {
701+ for x in 0..8 {
702+ p[y * 8 + x] = if x == 7 && y == 7 {
703+ (ft[14] + 3 * ft[15] + 2) >> 2
704+ } else {
705+ (ft[x + y] + 2 * ft[x + y + 1] + ft[x + y + 2] + 2) >> 2
706+ };
707+ }
708+ }
709+ }
710+ 4 => {
711+ for y in 0..8i32 {
712+ for x in 0..8i32 {
713+ p[(y * 8 + x) as usize] = if x > y {
714+ (ttf(x - y - 2) + 2 * ttf(x - y - 1) + ttf(x - y) + 2) >> 2
715+ } else if x < y {
716+ (llf(y - x - 2) + 2 * llf(y - x - 1) + llf(y - x) + 2) >> 2
717+ } else {
718+ (ft[0] + 2 * fc + fl[0] + 2) >> 2
719+ };
720+ }
721+ }
722+ }
723+ 5 => {
724+ for y in 0..8i32 {
725+ for x in 0..8i32 {
726+ let zvr = 2 * x - y;
727+ let k = x - (y >> 1);
728+ p[(y * 8 + x) as usize] = if zvr >= 0 && zvr % 2 == 0 {
729+ (ttf(k - 1) + ttf(k) + 1) >> 1
730+ } else if zvr >= 0 {
731+ (ttf(k - 2) + 2 * ttf(k - 1) + ttf(k) + 2) >> 2
732+ } else if zvr == -1 {
733+ (fl[0] + 2 * fc + ft[0] + 2) >> 2
734+ } else {
735+ let j = y - 2 * x;
736+ (llf(j - 1) + 2 * llf(j - 2) + llf(j - 3) + 2) >> 2
737+ };
738+ }
739+ }
740+ }
741+ 6 => {
742+ for y in 0..8i32 {
743+ for x in 0..8i32 {
744+ let zhd = 2 * y - x;
745+ let k = y - (x >> 1);
746+ p[(y * 8 + x) as usize] = if zhd >= 0 && zhd % 2 == 0 {
747+ (llf(k - 1) + llf(k) + 1) >> 1
748+ } else if zhd >= 0 {
749+ (llf(k - 2) + 2 * llf(k - 1) + llf(k) + 2) >> 2
750+ } else if zhd == -1 {
751+ (fl[0] + 2 * fc + ft[0] + 2) >> 2
752+ } else {
753+ let j = x - 2 * y;
754+ (ttf(j - 1) + 2 * ttf(j - 2) + ttf(j - 3) + 2) >> 2
755+ };
756+ }
757+ }
758+ }
759+ 7 => {
760+ for y in 0..8 {
761+ for x in 0..8 {
762+ let k = x + (y >> 1);
763+ p[y * 8 + x] = if y % 2 == 0 {
764+ (ft[k] + ft[k + 1] + 1) >> 1
765+ } else {
766+ (ft[k] + 2 * ft[k + 1] + ft[k + 2] + 2) >> 2
767+ };
768+ }
769+ }
770+ }
771+ _ => {
772+ // Horizontal-up (mode 8) — 8×8 thresholds (zHU up to 13 special).
773+ for y in 0..8 {
774+ for x in 0..8 {
775+ let zhu = x + 2 * y;
776+ let k = y + (x >> 1);
777+ p[y * 8 + x] = if zhu < 13 && zhu % 2 == 0 {
778+ (fl[k] + fl[k + 1] + 1) >> 1
779+ } else if zhu < 13 {
780+ (fl[k] + 2 * fl[k + 1] + fl[k + 2] + 2) >> 2
781+ } else if zhu == 13 {
782+ (fl[6] + 3 * fl[7] + 2) >> 2
783+ } else {
784+ fl[7]
785+ };
786+ }
787+ }
788+ }
789+ }
790+ let mut out = [0u8; 64];
791+ for i in 0..64 {
792+ out[i] = clip_u8(p[i]);
793+ }
794+ out
795+}
796+
797+/// Reconstructs an 8×8 block: inverse-transform the dequantized coefficients,
798+/// add the prediction, clip. (The 8×8 inverse transform lives in `transform`.)
799+pub fn add_residual_8x8(res: &[i32; 64], pred: &[i32; 64]) -> [u8; 64] {
800+ let _g = crate::prof::scope(crate::prof::Stage::Reconstruct);
801+ let mut out = [0u8; 64];
802+ for i in 0..64 {
803+ out[i] = clip_u8(pred[i] + res[i]);
804+ }
805+ out
806+}
807+
808+#[cfg(test)]
809+mod tests {
810+ use super::*;
811+
812+ #[test]
813+ fn intra8x8_dc_no_neighbors_is_128() {
814+ let p = intra8x8_pred(2, false, false, false, &[0; 16], &[0; 8], 0);
815+ assert!(p.iter().all(|&v| v == 128));
816+ }
817+
818+ #[test]
819+ fn intra8x8_vertical_copies_filtered_top() {
820+ // Flat top → filtered top is the same flat value → every column equals it.
821+ let p = intra8x8_pred(0, true, false, false, &[90; 16], &[0; 8], 0);
822+ assert!(p.iter().all(|&v| v == 90));
823+ }
824+
825+ #[test]
826+ fn intra8x8_horizontal_is_constant_per_row() {
827+ let mut left = [0u8; 8];
828+ for (i, v) in left.iter_mut().enumerate() {
829+ *v = (10 * i + 20) as u8;
830+ }
831+ let p = intra8x8_pred(1, false, true, false, &[0; 16], &left, 0);
832+ // Each row constant; filtering blurs values but row 0..7 stay monotone-ish.
833+ for y in 0..8 {
834+ for x in 1..8 {
835+ assert_eq!(p[y * 8 + x], p[y * 8], "row {y} not constant");
836+ }
837+ }
838+ }
839+
840+ #[test]
841+ fn luma_dc_no_neighbors_is_128() {
842+ assert_eq!(luma16x16_dc(false, false, &[0; 16], &[0; 16]), 128);
843+ }
844+
845+ #[test]
846+ fn luma_dc_averages_neighbors() {
847+ let top = [100u8; 16];
848+ let left = [200u8; 16];
849+ // (1600 + 3200 + 16) >> 5 = 150
850+ assert_eq!(luma16x16_dc(true, true, &top, &left), 150);
851+ assert_eq!(luma16x16_dc(true, false, &top, &left), 100);
852+ assert_eq!(luma16x16_dc(false, true, &top, &left), 200);
853+ }
854+
855+ #[test]
856+ fn chroma_dc_unavailable_is_128() {
857+ let p = chroma8x8_dc(false, false, &[0; 8], &[0; 8]);
858+ assert!(p.iter().all(|&x| x == 128));
859+ }
860+
861+ #[test]
862+ fn chroma_qp_mapping() {
863+ assert_eq!(chroma_qp(20), 20);
864+ assert_eq!(chroma_qp(30), 29);
865+ assert_eq!(chroma_qp(51), 39);
866+ }
867+
868+ #[test]
869+ fn nc_derivation() {
870+ assert_eq!(nc_from_neighbors(Some(3), Some(4)), 4);
871+ assert_eq!(nc_from_neighbors(Some(5), None), 5);
872+ assert_eq!(nc_from_neighbors(None, None), 0);
873+ }
874+
875+ #[test]
876+ fn intra4x4_vertical_copies_top() {
877+ let top = [10, 20, 30, 40, 0, 0, 0, 0];
878+ let p = intra4x4_pred(0, true, false, &top, &[0; 4], 0);
879+ for y in 0..4 {
880+ assert_eq!(&p[y * 4..y * 4 + 4], &[10, 20, 30, 40]);
881+ }
882+ }
883+
884+ #[test]
885+ fn intra4x4_horizontal_copies_left() {
886+ let left = [11, 22, 33, 44];
887+ let p = intra4x4_pred(1, false, true, &[0; 8], &left, 0);
888+ for y in 0..4 {
889+ assert!(p[y * 4..y * 4 + 4].iter().all(|&v| v == left[y]));
890+ }
891+ }
892+
893+ #[test]
894+ fn intra4x4_dc_averages() {
895+ let top = [10, 10, 10, 10, 0, 0, 0, 0];
896+ let left = [30, 30, 30, 30];
897+ // (40 + 120 + 4) >> 3 = 20
898+ let p = intra4x4_pred(2, true, true, &top, &left, 0);
899+ assert!(p.iter().all(|&v| v == 20));
900+ // top only: (40 + 2) >> 2 = 10
901+ let p2 = intra4x4_pred(2, true, false, &top, &left, 0);
902+ assert!(p2.iter().all(|&v| v == 10));
903+ // neither: 128
904+ let p3 = intra4x4_pred(2, false, false, &top, &left, 0);
905+ assert!(p3.iter().all(|&v| v == 128));
906+ }
907+}
vendor/rusty_h264-common/src/prof.rsadded+585 -0
@@ -0,0 +1,585 @@
1+//! Feature-gated decode/encode **stage profiler** — the instrument for perf work.
2+//!
3+//! Zero cost unless the `profile` feature is enabled: with it off, [`scope`] is a
4+//! no-op returning a ZST guard that the optimizer elides entirely, so release
5+//! builds are byte-identical and the hot path is untouched. With it on, each
6+//! kernel times itself into an atomic nanosecond bucket; [`dump`] prints the
7+//! per-stage breakdown.
8+//!
9+//! Design mirrors `rff-codec-mp3`'s `encode::prof`. The kernels (`mc_luma`,
10+//! `reconstruct_4x4`, `decode_residual_block`, the intra predictors, `deblock`)
11+//! each open a [`scope`] at their top, so every call is captured with one edit.
12+//! A [`Stage::Total`] scope wraps the whole `decode()` call; the **`mgmt/other`**
13+//! line is the residue (`Total − Σ stages`) — i.e. per-MB management, MV
14+//! prediction, nnz/grid bookkeeping, dequant — the bucket we most want to shrink.
15+//!
16+//! Caveat for honest reading: the fine-grained buckets (`reconstruct`, `entropy`)
17+//! are entered millions of times, so each carries ~one `Instant::now()` of timer
18+//! overhead — their share is mildly inflated and `mgmt/other` mildly deflated.
19+//! The `(N calls)` column lets you judge ns/call. Measure **throughput** with the
20+//! `profile` feature OFF (no timer overhead); use this breakdown only to rank
21+//! stages.
22+
23+/// A timed pipeline stage. Order matters: everything before [`Total`](Stage::Total)
24+/// is a sub-component summed for the `mgmt/other` residue.
25+#[derive(Clone, Copy)]
26+pub enum Stage {
27+ Entropy = 0,
28+ IntraPred = 1,
29+ InterMc = 2,
30+ Reconstruct = 3,
31+ Deblock = 4,
32+ // --- Phase 1: decomposition of the former "mgmt/other" residue ---
33+ /// Inverse quantization (`dequantize*`, `inverse_quant_8x8`).
34+ Dequant = 5,
35+ /// Scattering a reconstructed block into the strided frame plane (`store`).
36+ Scatter = 6,
37+ /// Re-striding the MC output into the per-MB prediction buffer.
38+ PredBuf = 7,
39+ /// MV prediction + per-block motion/ref/coded grid writes.
40+ MvGrid = 8,
41+ // --- Phase 3 / ghost-tracking: further decomposition of the residue ---
42+ /// Neighbour derivation for prediction (MV/ref/intra-mode availability + reads).
43+ Neighbors = 9,
44+ /// P_Skip / B_Skip reconstruction (the pred→rec copies + grid writes, no residual).
45+ SkipRecon = 10,
46+ /// Per-frame finalize: output-frame build (crop), DPB / reference management.
47+ Finalize = 11,
48+ /// Per-MB non-residual syntax parse (mb_skip_run, mb_type, cbp, mb_qp_delta).
49+ Syntax = 12,
50+ /// `as_reference` DPB plane clone (rec_y/u/v → RefFrame), split out of Finalize.
51+ DpbClone = 13,
52+ // --- Encoder stages (a disjoint top-level partition of encode(); the shared
53+ // primitive scopes above — IntraPred/InterMc/Reconstruct/Deblock/Entropy —
54+ // nest INSIDE these and give the within-stage breakdown) ---
55+ /// `coded_source`: clamped copy of the source planes to the MB-aligned grid.
56+ EncSource = 14,
57+ /// P_Skip prediction + free-skip check (skip MC + SAD + commit).
58+ EncSkip = 15,
59+ /// Motion estimation: `best_part` (integer SAD search + sub-pel + SATD/λ cost).
60+ EncMe = 16,
61+ /// Intra mode cost inside the inter decision (`best_i16_sad`/`best_i16_satd`).
62+ EncIntraCost = 17,
63+ /// Coding a chosen inter MB (`encode_inter_mb`: MC, residual, T/Q, entropy, recon).
64+ EncInterCode = 18,
65+ /// Coding an intra MB (`encode_mb`: mode search + T/Q + entropy + recon).
66+ EncIntraCode = 19,
67+ /// Per-frame encoder finalize (deblock-info build + RefFrame handoff).
68+ EncFinal = 20,
69+ /// Forward transform + quantize (+ recon dequant/idct) inside MB coding — INFO (nested).
70+ EncTq = 21,
71+ /// CAVLC residual bit-writing — INFO (nested inside Enc*Code).
72+ EncWrite = 22,
73+ /// The skip free-check's forward T/Q proof — INFO (nested inside EncSkip).
74+ EncFree = 23,
75+ /// Per-frame encoder PREP before the macroblock loop (FrameEncoder grid
76+ /// allocation, source copy, AQ/mb-tree QP maps, content pre-passes) — INFO
77+ /// (nested; contains `EncSource`).
78+ EncPrep = 24,
79+ /// NAL assembly of the coded slice: RBSP emulation-prevention scan + the
80+ /// Annex-B copy into the output buffer. A full byte-wise pass over the frame's
81+ /// bitstream, invisible until it was named.
82+ EncNal = 25,
83+ /// The whole macroblock double-loop — INFO (nested; contains the Enc* per-MB
84+ /// stages). `EncMbLoop − Σ(per-MB stages)` is the per-MB GLUE, the part of the
85+ /// old `mgmt/other` that lives between the named steps.
86+ EncMbLoop = 26,
87+ /// Per-MB motion-vector predictor / neighbour-candidate build in the encode
88+ /// loop (`mv_neighbors_block`) — INFO (nested inside `EncMbLoop`, part of the
89+ /// per-MB glue being decomposed).
90+ EncMvPred = 27,
91+ /// CAVLC entropy EMIT for a planned macroblock (`emit_inter_cavlc` and the
92+ /// intra equivalent): mb_type, ref_idx, mvd, cbp, mb_qp_delta and every
93+ /// residual block. This sits OUTSIDE `plan_inter_mb`, so before it was named
94+ /// the whole encoder-side entropy coder was landing in `mgmt/other`.
95+ EncEmit = 28,
96+ /// Per-MB boundary-strength derivation done INSIDE the encode loop — INFO
97+ /// (nested in `EncMbLoop`). Named so the work moved out of deblocking can be
98+ /// priced at its new location rather than inferred from stage deltas.
99+ EncBs = 29,
100+ /// Adaptive-quantization per-MB QP map (`aq_qp_map`) — a full-frame variance
101+ /// pass that runs every frame because AQ is on by default. INFO (nested in
102+ /// `EncPrep`).
103+ EncAq = 30,
104+ /// Sub-pel prediction served from the cached half-pel planes (`hpel_block`) —
105+ /// INFO (nested in `EncMe`). Named because the plane cache MOVED the sub-pel
106+ /// motion-search work out of `inter-mc`, and unnamed work is invisible work.
107+ MeHpel = 31,
108+ /// The motion search's SATD/SAD cost metric itself — INFO (nested in `EncMe`).
109+ MeCost = 32,
110+ /// Building the cached half-pel planes for one reference picture — INFO.
111+ MeHpelBuild = 33,
112+ /// ME: coarse-to-fine full-pel diamond — INFO (nested in `EncMe`).
113+ MeDiamond = 34,
114+ /// ME: sub-pel (half + quarter) refinement rings — INFO (nested in `EncMe`).
115+ MeSubpel = 35,
116+ /// ME: the stalled-diamond wide rescue grid — INFO (nested in `EncMe`).
117+ MeRescue = 36,
118+ /// Wraps the whole `decode()`/`encode()` call — the denominator.
119+ Total = 37,
120+ // --- H-32: decomposition of the decoder's per-MB residue (INFO, nested;
121+ // indexes past `Total` are excluded from dump()'s residue sum) ---
122+ /// CABAC P-inter MB branch, whole body (parse + MC + recon nested inside).
123+ DecMbP = 38,
124+ /// CABAC B MB branch, whole body.
125+ DecMbB = 39,
126+ /// CABAC intra path (mode parse + residual + recon), whole body.
127+ DecMbI = 40,
128+ /// B-direct derivation + MC (`decode_b_direct`) — INFO (nested in DecMbB).
129+ DecBDirect = 41,
130+ /// Bi-/uni-pred region MC + blend (`b_mc`) — INFO (nested in DecMbB).
131+ DecBMc = 42,
132+ /// Per-picture + per-slice setup: FrameDecoder grids, slice neighbour vecs.
133+ DecSetup = 43,
134+ /// B-direct DERIVATION only (neighbours, ref pick, colZero gather) — INFO.
135+ DecBDeriv = 44,
136+ /// B motion-grid commit (`b_set_motion`) — INFO (nested in DecMbB).
137+ DecBSet = 45,
138+ // --- H-38: decomposition of `b_mc` (INFO, nested in DecBMc) ---
139+ /// Implicit-weight derivation (POC math + the integer divide).
140+ DecBWeights = 46,
141+ /// Luma MC calls inside `b_mc`.
142+ DecBLuma = 47,
143+ /// Chroma MC calls inside `b_mc`.
144+ DecBChroma = 48,
145+ /// The bi-pred blend / uni-pred row copies out of the staging buffers.
146+ DecBBlend = 49,
147+ // --- Entropy-stage decomposition (INFO, nested inside `Entropy`) — added for
148+ // the CABAC/CAVLC diagnosis once sampled profiling made sub-scopes affordable.
149+ /// CABAC residual: the coded_block_flag bin + its neighbour-context read.
150+ EntCbf = 50,
151+ /// CABAC residual: the significance-map loop (sig + last bins).
152+ EntSig = 51,
153+ /// CABAC residual: the level loop (one/abs/UEG0 bins + sign bypass).
154+ EntLvl = 52,
155+ /// CAVLC residual: the coeff_token VLC read.
156+ CavTok = 53,
157+ /// CAVLC residual: trailing-one signs + level prefix/suffix reads.
158+ CavLvl = 54,
159+ /// CAVLC residual: total_zeros + run_before reads and the scatter to scan order.
160+ CavRun = 55,
161+ /// Per-MB neighbour/state cache shuffling in the CABAC MB branches: the
162+ /// mvd/ref 30-entry cache build, the 48-entry nzc cache build, and the mb_nzc
163+ /// write-back — the state plumbing BETWEEN parse steps (INFO, nested).
164+ DecStateCache = 56,
165+ /// `add_inter_residual` whole body (INFO, nested): contains Dequant /
166+ /// Reconstruct / Scatter leaves; body minus leaves = the residual-add glue
167+ /// (nnz re-derivation scans, un-scan, pred gathers, loop skeleton).
168+ DecResidAdd = 57,
169+ /// The P-body MC staging block (INFO, nested): contains InterMc + PredBuf
170+ /// leaves; block minus leaves = rect-ladder + staging-buffer cost.
171+ DecMcStage = 58,
172+ /// `pack_frame_into` — the per-frame MbPack build (INFO, nested in Deblock).
173+ DebPack = 59,
174+ /// Per-MB bS derivation inside `filter_frame`: kind gate, predicates,
175+ /// packed/tile/blind derivation, bs materialization (INFO, nested in Deblock).
176+ DebDerive = 60,
177+ /// Annex-B start-code scan (`split_annex_b`) — a full byte-wise pass over the
178+ /// WHOLE stream plus two Vec allocations. Entered ~once per access unit, so it
179+ /// is in the low-call-count regime the profiler measures reliably.
180+ DecNalSplit = 61,
181+ /// RBSP emulation-prevention removal (`emulation_unprevent`) — a second full
182+ /// byte-wise pass, one bounds-checked `push` per byte, into a fresh Vec per NAL.
183+ DecRbsp = 62,
184+ /// The 11 per-slice `vec![...; total_mbs]` neighbour-state allocations at the top
185+ /// of `decode_slice_cabac_inner` (mvd grids alone are 64 B/MB each, twice).
186+ DecSliceAlloc = 63,
187+ /// The whole CABAC macroblock loop — INFO (nested; contains dec-mb-P/B/I).
188+ /// `DecMbLoop - sum(dec-mb-*)` is the per-MB loop GLUE outside the MB bodies.
189+ DecMbLoop = 64,
190+ /// `row_hook` — on every MB after decode. Mid-row calls early-out (no scope)
191+ /// unless `RS_H264_ROWHOOK_EAGER=1`. On row crossings: bS derive + filter /
192+ /// EDC row handoff. INFO (nested in DecMbLoop; contains deb:derive + deblock).
193+ ///
194+ /// Call COUNT with the early-out ≈ MB rows/picture (exact). Quote ms only with
195+ /// that count; per-MB eager scoping inflated both calls and self-tax.
196+ DecRowHook = 65,
197+}
198+
199+/// Number of buckets.
200+pub const N: usize = 66;
201+
202+#[cfg(feature = "profile")]
203+mod imp {
204+ use super::{Stage, N};
205+ use std::sync::atomic::{AtomicU64, Ordering};
206+ use std::sync::Mutex;
207+ use std::time::Instant;
208+
209+ /// Index of the first non-`Total` stage — the residue sum runs `0..SUB`.
210+ const SUB: usize = Stage::Total as usize;
211+
212+ /// A cheap monotonic tick. On x86_64 this is `rdtsc` (~5-10 ns, ~3-5× cheaper
213+ /// than `Instant::now()` = QueryPerformanceCounter ~20-30 ns on Windows), which
214+ /// is what dominated the profiler's own overhead (~1M scope entries × 2 calls).
215+ /// Buckets accumulate *ticks*; `dump()` converts to ns via a run-length TSC
216+ /// calibration (invariant TSC → ticks are wall-time-proportional). Elsewhere we
217+ /// fall back to `Instant` nanos so the profiler still builds cross-arch.
218+ #[cfg(target_arch = "x86_64")]
219+ #[inline(always)]
220+ fn ticks() -> u64 {
221+ // SAFETY: `_rdtsc` is a pure timestamp read with no memory effects; it is
222+ // `unsafe` only because it is a target intrinsic. Reordering is immaterial to
223+ // coarse scope timing. Compiled only under `feature = "profile"` (dev tool).
224+ unsafe { core::arch::x86_64::_rdtsc() }
225+ }
226+ #[cfg(not(target_arch = "x86_64"))]
227+ #[inline(always)]
228+ fn ticks() -> u64 {
229+ use std::sync::OnceLock;
230+ static EPOCH: OnceLock<Instant> = OnceLock::new();
231+ EPOCH.get_or_init(Instant::now).elapsed().as_nanos() as u64
232+ }
233+
234+ /// (wall-clock, tick-count) sampled at `reset()` — the calibration anchor read at
235+ /// `dump()` to recover ns-per-tick. Touched twice per run, so its `Mutex` cost is
236+ /// irrelevant next to the per-scope path.
237+ static ANCHOR: Mutex<Option<(Instant, u64)>> = Mutex::new(None);
238+
239+ const NAMES: [&str; N] = [
240+ "entropy/cavlc",
241+ "intra-pred",
242+ "inter-mc",
243+ "reconstruct",
244+ "deblock",
245+ "dequant",
246+ "scatter(store)",
247+ "pred-buf copy",
248+ "mv+grid",
249+ "neighbors",
250+ "skip-recon",
251+ "finalize",
252+ "syntax-parse",
253+ "dpb-clone",
254+ "enc-source-copy",
255+ "enc-skip-check",
256+ "enc-me(best_part)",
257+ "enc-intra-cost",
258+ "enc-inter-code",
259+ "enc-intra-code",
260+ "enc-finalize",
261+ "enc-T/Q(nested)",
262+ "enc-cavlc-write(nested)",
263+ "enc-skip-freecheck(nested)",
264+ "enc-prep(nested)",
265+ "enc-nal-assembly",
266+ "enc-mb-loop(nested)",
267+ "enc-mvpred(nested)",
268+ "enc-cavlc-emit",
269+ "enc-bs-derive(nested)",
270+ "enc-aq-map(nested)",
271+ "me-hpel-read(nested)",
272+ "me-cost/satd(nested)",
273+ "me-hpel-BUILD(nested)",
274+ "me-diamond(nested)",
275+ "me-subpel(nested)",
276+ "me-rescue(nested)",
277+ "TOTAL",
278+ "dec-mb-P(nested)",
279+ "dec-mb-B(nested)",
280+ "dec-mb-I(nested)",
281+ "b-direct(nested)",
282+ "b-mc(nested)",
283+ "dec-setup",
284+ "b-deriv(nested)",
285+ "b-setmotion(nested)",
286+ "b:weights(nested)",
287+ "b:luma-mc(nested)",
288+ "b:chroma-mc(nested)",
289+ "b:blend(nested)",
290+ "ent:cbf(nested)",
291+ "ent:sigmap(nested)",
292+ "ent:levels(nested)",
293+ "cav:token(nested)",
294+ "cav:levels(nested)",
295+ "cav:runs(nested)",
296+ "state-cache(nested)",
297+ "resid-add(nested)",
298+ "mc-stage(nested)",
299+ "deb:pack(nested)",
300+ "deb:derive(nested)",
301+ "dec-nal-split",
302+ "dec-rbsp-unescape",
303+ "dec-slice-alloc",
304+ "dec-mb-loop(nested)",
305+ "dec-row-hook(nested)",
306+ ];
307+
308+ static NS: [AtomicU64; N] = [const { AtomicU64::new(0) }; N];
309+ static CALLS: [AtomicU64; N] = [const { AtomicU64::new(0) }; N];
310+
311+ /// SAMPLED PROFILING — the fix for the profiler's own tax.
312+ ///
313+ /// The scope guard is an rdtsc pair. At ~20M per-macroblock scopes that tax was
314+ /// measured at **1.32-1.43x of whole decode**, which is why every per-MB stage
315+ /// share in this codec has been untrustworthy and why the campaign fell back to
316+ /// ablation (which can only price stages someone already put a knob on).
317+ ///
318+ /// Fix: only TIME one call in `RS_H264_PROF_SAMPLE` (default 1 = time every call,
319+ /// preserving the old behaviour exactly). Sampled cycles are scaled back up by the
320+ /// sampling period, so the SHARE each stage reports is unbiased — a stage that
321+ /// takes x% of time is entered proportionally often, so timing 1-in-N calls
322+ /// estimates the same x% with 1/N the tax. Call COUNTS stay exact (counting is a
323+ /// single relaxed add, not an rdtsc pair, so it is not the expensive part).
324+ ///
325+ /// This is the standard statistical-profiling trade: precision for a smaller
326+ /// probe. At N=64 the tax drops ~64x while a stage above ~1% still lands within a
327+ /// few percent relative over 20M+ entries.
328+ pub struct Guard {
329+ stage: usize,
330+ start: u64,
331+ /// 0 = not timed. Otherwise the weight this sample carries: 1 for an exactly
332+ /// timed call, N for a sampled one.
333+ scale: u64,
334+ }
335+
336+ /// Calls below this are ALWAYS timed exactly, whatever the sampling period.
337+ ///
338+ /// Two reasons. (a) The tax is proportional to call count, so a stage entered a
339+ /// few thousand times costs nothing to time in full — sampling it buys no speed.
340+ /// (b) Sampling a low-count stage is statistically worthless: `Total` is entered
341+ /// once per FRAME (60 calls on a 60-frame clip), so at N=64 it would estimate the
342+ /// entire denominator from ONE sample. Since every share is a ratio to `Total`,
343+ /// that one bad estimate would skew every share on the table — which is exactly
344+ /// what the first N=64 run showed (every stage share rose together).
345+ const EXACT_PREFIX: u64 = 8192;
346+
347+ /// Sampling period. 1 = time everything (previous behaviour, and the default so
348+ /// no existing measurement silently changes meaning).
349+ pub(crate) static SAMPLE_N: std::sync::atomic::AtomicU64 =
350+ std::sync::atomic::AtomicU64::new(0);
351+
352+ /// Sampling period, ROUNDED UP TO A POWER OF TWO so the selection test is a mask
353+ /// (1 cycle) and not a `u64` division (~20-40 cycles — as expensive as the rdtsc
354+ /// it is meant to avoid, which would make the whole scheme pointless).
355+ #[inline(always)]
356+ fn sample_period() -> u64 {
357+ match SAMPLE_N.load(Ordering::Relaxed) {
358+ 0 => {
359+ let n = std::env::var("RS_H264_PROF_SAMPLE")
360+ .ok()
361+ .and_then(|v| v.parse::<u64>().ok())
362+ .filter(|v| *v >= 1)
363+ .unwrap_or(1)
364+ .next_power_of_two();
365+ SAMPLE_N.store(n, Ordering::Relaxed);
366+ n
367+ }
368+ n => n,
369+ }
370+ }
371+
372+ impl Drop for Guard {
373+ #[inline]
374+ fn drop(&mut self) {
375+ if self.scale != 0 {
376+ let d = ticks().wrapping_sub(self.start);
377+ // Weight by this sample's scale so the bucket estimates TOTAL cycles.
378+ // The first EXACT_PREFIX calls carry weight 1 (they were all timed);
379+ // the tail carries weight N. Sum = exact prefix + unbiased estimate of
380+ // the remainder, so a short-running stage degrades to "fully timed"
381+ // rather than to "one sample times N".
382+ NS[self.stage].fetch_add(d.wrapping_mul(self.scale), Ordering::Relaxed);
383+ }
384+ CALLS[self.stage].fetch_add(1, Ordering::Relaxed);
385+ }
386+ }
387+
388+ #[inline]
389+ /// Descent E: the raw tick source, for census modules that accumulate cycles into
390+ /// their own buckets rather than a `Stage`.
391+ #[inline(always)]
392+ pub fn tick() -> u64 {
393+ ticks()
394+ }
395+
396+ pub fn scope(s: Stage) -> Guard {
397+ let n = sample_period();
398+ let c = CALLS[s as usize].load(Ordering::Relaxed);
399+ // Pick 1-in-N by HASHING the call index, not by striding it.
400+ //
401+ // A plain `c % N` stride aliases: decode work is intensely periodic (blocks
402+ // per macroblock, macroblocks per row), so a power-of-two stride can lock onto
403+ // the same position in that pattern every time and systematically sample only
404+ // the cheap — or only the expensive — calls. Multiplying by the 64-bit golden
405+ // ratio and taking high bits decorrelates the selection from any workload
406+ // period, giving an unbiased 1-in-N at ~4 cycles (mul, shift, and, test).
407+ const GOLDEN: u64 = 0x9E37_79B9_7F4A_7C15;
408+ let scale = if n == 1 || c < EXACT_PREFIX {
409+ 1
410+ } else if (c.wrapping_mul(GOLDEN) >> 32) & (n - 1) == 0 {
411+ n
412+ } else {
413+ 0
414+ };
415+ Guard {
416+ stage: s as usize,
417+ start: if scale != 0 { ticks() } else { 0 },
418+ scale,
419+ }
420+ }
421+
422+ /// Zero all buckets and sample the calibration anchor — call before a clean run.
423+ pub fn reset() {
424+ for a in NS.iter().chain(CALLS.iter()) {
425+ a.store(0, Ordering::Relaxed);
426+ }
427+ *ANCHOR.lock().unwrap() = Some((Instant::now(), ticks()));
428+ }
429+
430+ /// Human-readable name for stage index `i` (`SUB` = the `TOTAL` row).
431+ pub fn name(i: usize) -> &'static str {
432+ NAMES.get(i).copied().unwrap_or("?")
433+ }
434+
435+ /// One calibrated reading: `(ms, calls)` per stage index `0..N` (index `SUB` is
436+ /// `Total`). Buckets hold `rdtsc` cycles; ns/tick is recovered from the reset→now
437+ /// anchor (elapsed wall / elapsed cycles — invariant TSC, so cycles are wall-
438+ /// proportional). Lets a driver run many passes and take a per-stage median.
439+ pub fn snapshot() -> [(f64, u64); N] {
440+ let load = |i: usize| NS[i].load(Ordering::Relaxed);
441+ let ns_per_tick = ANCHOR
442+ .lock()
443+ .unwrap()
444+ .map(|(t0, c0)| {
445+ let wall = t0.elapsed().as_nanos() as f64;
446+ let cyc = ticks().wrapping_sub(c0) as f64;
447+ if cyc > 0.0 {
448+ wall / cyc
449+ } else {
450+ 1.0
451+ }
452+ })
453+ .unwrap_or(1.0);
454+ let mut out = [(0.0f64, 0u64); N];
455+ for (i, o) in out.iter_mut().enumerate() {
456+ *o = (load(i) as f64 * ns_per_tick / 1e6, CALLS[i].load(Ordering::Relaxed));
457+ }
458+ out
459+ }
460+
461+ /// Print the per-stage breakdown (does not reset).
462+ pub fn dump() {
463+ let s = snapshot();
464+ let total = s[SUB].0.max(1e-9);
465+ let sub_sum: f64 = (0..SUB).map(|i| s[i].0).sum();
466+ let mgmt = (total - sub_sum).max(0.0);
467+ let pct = |ms: f64| 100.0 * ms / total;
468+
469+ eprintln!("\n--- decode stage profile (decode() wall = {total:.1} ms) ---");
470+ for i in 0..SUB {
471+ eprintln!(
472+ " {:<15} {:>8.1} ms {:>5.1}% ({} calls)",
473+ NAMES[i], s[i].0, pct(s[i].0), s[i].1,
474+ );
475+ }
476+ eprintln!(
477+ " {:<15} {:>8.1} ms {:>5.1}% <- the OTHER bucket: unnamed decode glue",
478+ "mgmt/other", mgmt, pct(mgmt),
479+ );
480+ eprintln!(" {:<15} {:>8.1} ms 100.0%", NAMES[SUB], total);
481+ // Attribute OTHER using INFO scopes (nested; shares can overlap parents).
482+ // These are the deployment-signal names for the 1T residue campaign.
483+ let info = |st: Stage| s[st as usize];
484+ let loop_ms = info(Stage::DecMbLoop).0;
485+ let mb_bodies = info(Stage::DecMbP).0 + info(Stage::DecMbB).0 + info(Stage::DecMbI).0;
486+ let loop_glue = (loop_ms - mb_bodies).max(0.0);
487+ eprintln!("--- OTHER attribution (INFO scopes; parents include children) ---");
488+ eprintln!(
489+ " dec-mb-loop glue≈ {:>8.1} ms {:>5.1}% (loop {:.1} − P/B/I bodies {:.1})",
490+ loop_glue,
491+ pct(loop_glue),
492+ loop_ms,
493+ mb_bodies
494+ );
495+ let row_hook = info(Stage::DecRowHook).0;
496+ let deblock = s[Stage::Deblock as usize].0;
497+ let syntax = s[Stage::Syntax as usize].0;
498+ let inter = s[Stage::InterMc as usize].0;
499+ let entropy = s[Stage::Entropy as usize].0;
500+ // Residue naming: top-level OTHER is work NOT wrapped by stages 0..Total.
501+ // INFO scopes after Total do not shrink OTHER — they NAME pieces of it.
502+ // Reconcile the big pieces that live in OTHER (nested times overlap).
503+ eprintln!("--- OTHER named (why ~45% is not a mystery kernel) ---");
504+ eprintln!(
505+ " top-level leaves already subtract: entropy {:.1}% inter-mc {:.1}% deblock {:.1}% syntax {:.1}%",
506+ pct(entropy),
507+ pct(inter),
508+ pct(deblock),
509+ pct(syntax),
510+ );
511+ eprintln!(
512+ " in-OTHER orchestration (INFO; overlaps leaves): row-hook {:.1}% loop-glue {:.1}% (glue−hook≈{:.1}%)",
513+ pct(row_hook),
514+ pct(loop_glue),
515+ pct((loop_glue - row_hook).max(0.0)),
516+ );
517+ eprintln!(
518+ " in-OTHER B glue (INFO nested): b-mc {:.1}% b-direct {:.1}% blend {:.1}% setmot {:.1}% deriv {:.1}%",
519+ pct(info(Stage::DecBMc).0),
520+ pct(info(Stage::DecBDirect).0),
521+ pct(info(Stage::DecBBlend).0),
522+ pct(info(Stage::DecBSet).0),
523+ pct(info(Stage::DecBDeriv).0),
524+ );
525+ eprintln!(
526+ " in-OTHER resid/mc-stage (INFO): resid-add {:.1}% mc-stage {:.1}% — remainder ≈ timer tax + tiny parse glue",
527+ pct(info(Stage::DecResidAdd).0),
528+ pct(info(Stage::DecMcStage).0),
529+ );
530+ for st in [
531+ Stage::DecMbB,
532+ Stage::DecMbP,
533+ Stage::DecMbI,
534+ Stage::DecBDirect,
535+ Stage::DecBMc,
536+ Stage::DecRowHook,
537+ Stage::DecResidAdd,
538+ Stage::DecMcStage,
539+ Stage::DecSetup,
540+ Stage::DecSliceAlloc,
541+ Stage::DecNalSplit,
542+ Stage::DecRbsp,
543+ ] {
544+ let (ms, calls) = info(st);
545+ if ms > 0.05 || calls > 0 {
546+ eprintln!(
547+ " {:<18} {:>8.1} ms {:>5.1}% ({} calls)",
548+ NAMES[st as usize],
549+ ms,
550+ pct(ms),
551+ calls
552+ );
553+ }
554+ }
555+ }
556+}
557+
558+#[cfg(not(feature = "profile"))]
559+mod imp {
560+ use super::{Stage, N};
561+
562+ /// No-op guard (ZST) — elided in release.
563+ pub struct Guard;
564+
565+ #[inline(always)]
566+ pub fn scope(_s: Stage) -> Guard {
567+ Guard
568+ }
569+ #[inline(always)]
570+ pub fn reset() {}
571+ #[inline(always)]
572+ pub fn dump() {}
573+ #[inline(always)]
574+ pub fn snapshot() -> [(f64, u64); N] {
575+ [(0.0, 0); N]
576+ }
577+ #[inline(always)]
578+ pub fn name(_i: usize) -> &'static str {
579+ ""
580+ }
581+}
582+
583+pub use imp::{dump, name, reset, scope, snapshot, Guard};
584+#[cfg(feature = "profile")]
585+pub use imp::tick;
vendor/rusty_h264-common/src/transform.rsadded+1561 -0
@@ -0,0 +1,1561 @@
1+//! H.264 4×4 residual transform and quantization (spec §8.5 / §8.6).
2+//!
3+//! H.264 uses a small integer approximation of the DCT — a 4×4 "core" transform
4+//! whose scaling is folded into the quantizer, so it is exactly invertible in
5+//! integer arithmetic. This module implements the forward path (encoder:
6+//! residual → coefficients → quantized levels) and the inverse path (decoder
7+//! and encoder-reconstruction: levels → coefficients → residual).
8+//!
9+//! Correctness here is non-negotiable: the levels we emit are dequantized by
10+//! every conforming decoder using the exact spec tables below, so the forward
11+//! quantizer must be the faithful inverse of that process.
12+
13+/// `normAdjust4x4` (spec Table — the dequant scaling V), indexed by `[QP % 6]`
14+/// then by position group (see [`pos_group`]).
15+const NORM_ADJUST: [[i32; 3]; 6] = [
16+ [10, 16, 13],
17+ [11, 18, 14],
18+ [13, 20, 16],
19+ [14, 23, 18],
20+ [16, 25, 20],
21+ [18, 29, 23],
22+];
23+
24+/// Forward quantization multipliers `MF`, indexed by `[QP % 6]` then position
25+/// group. Paired with [`NORM_ADJUST`] so reconstruction ≈ source.
26+const QUANT_MF: [[i32; 3]; 6] = [
27+ [13107, 5243, 8066],
28+ [11916, 4660, 7490],
29+ [10082, 4194, 6554],
30+ [9362, 3647, 5825],
31+ [8192, 3355, 5243],
32+ [7282, 2893, 4559],
33+];
34+
35+/// Position group within a 4×4 block:
36+/// - 0: both indices even — the (0,0),(0,2),(2,0),(2,2) positions,
37+/// - 1: both indices odd — (1,1),(1,3),(3,1),(3,3),
38+/// - 2: everything else.
39+#[inline]
40+fn pos_group(i: usize, j: usize) -> usize {
41+ match (i % 2, j % 2) {
42+ (0, 0) => 0,
43+ (1, 1) => 1,
44+ _ => 2,
45+ }
46+}
47+
48+/// `pos_group` evaluated for all 16 raster positions — lets the hot quant/dequant
49+/// loops index a flat per-position table instead of recomputing the `(i%2, j%2)`
50+/// match per coefficient (openh264 stores per-position MF/dequant tables).
51+const POS_GROUP_FLAT: [usize; 16] = [0, 2, 0, 2, 2, 1, 2, 1, 0, 2, 0, 2, 2, 1, 2, 1];
52+
53+
54+/// `16 · NORM_ADJUST` pre-expanded to a flat 16-entry LevelScale table per `qp % 6`.
55+const fn flatten_level_scale() -> [[i32; 16]; 6] {
56+ let mut out = [[0i32; 16]; 6];
57+ let mut m = 0;
58+ while m < 6 {
59+ let mut idx = 0;
60+ while idx < 16 {
61+ out[m][idx] = 16 * NORM_ADJUST[m][POS_GROUP_FLAT[idx]];
62+ idx += 1;
63+ }
64+ m += 1;
65+ }
66+ out
67+}
68+const LEVEL_SCALE_FLAT: [[i32; 16]; 6] = flatten_level_scale();
69+
70+/// One-dimensional forward core transform butterfly (rows of `Cf`).
71+#[inline]
72+fn fwd_1d(x0: i32, x1: i32, x2: i32, x3: i32) -> (i32, i32, i32, i32) {
73+ let t0 = x0 + x3;
74+ let t1 = x1 + x2;
75+ let t2 = x1 - x2;
76+ let t3 = x0 - x3;
77+ (t0 + t1, 2 * t3 + t2, t0 - t1, t3 - 2 * t2)
78+}
79+
80+/// One-dimensional inverse core transform butterfly (rows of `Ci`).
81+#[inline]
82+fn inv_1d(d0: i32, d1: i32, d2: i32, d3: i32) -> (i32, i32, i32, i32) {
83+ let e0 = d0 + d2;
84+ let e1 = d0 - d2;
85+ let e2 = (d1 >> 1) - d3;
86+ let e3 = d1 + (d3 >> 1);
87+ (e0 + e3, e1 + e2, e1 - e2, e0 - e3)
88+}
89+
90+/// Forward core transform `W = Cf · X · Cfᵀ` over a row-major 4×4 block.
91+/// The output coefficients are pre-quantization (scaling lives in the quantizer).
92+pub fn forward_core(block: &[i32; 16]) -> [i32; 16] {
93+ let mut m = *block;
94+ // Rows.
95+ for r in 0..4 {
96+ let (a, b, c, d) = fwd_1d(m[r * 4], m[r * 4 + 1], m[r * 4 + 2], m[r * 4 + 3]);
97+ m[r * 4] = a;
98+ m[r * 4 + 1] = b;
99+ m[r * 4 + 2] = c;
100+ m[r * 4 + 3] = d;
101+ }
102+ // Columns.
103+ for c in 0..4 {
104+ let (a, b, cc, d) = fwd_1d(m[c], m[4 + c], m[8 + c], m[12 + c]);
105+ m[c] = a;
106+ m[4 + c] = b;
107+ m[8 + c] = cc;
108+ m[12 + c] = d;
109+ }
110+ m
111+}
112+
113+/// Quantizes forward-transform coefficients to levels. `intra` selects the
114+/// rounding dead-zone offset (1/3 for intra, 1/6 for inter).
115+/// Scalar quantization. `dz_div` sets the rounding dead-zone: the offset added
116+/// before the right shift is `2^qbits / dz_div`, so a *smaller* `dz_div` rounds
117+/// up more (higher quality, more bits). Typical values: 6 for inter, 3 for an
118+/// I-frame that serves as a reference, 2 for all-intra (where the larger offset
119+/// is a net rate-distortion win — better-quantized blocks predict their
120+/// neighbors better, shrinking downstream residuals).
121+pub fn quantize(coeffs: &[i32; 16], qp: u8, dz_div: i64) -> [i32; 16] {
122+ // openh264's quant STRUCTURE (`level = ((|c| + FF)·MF_oh) >> 16`, bit-identical to
123+ // `WelsQuant4x4_sse2`'s pmulhuw high-word) carrying OUR deadzone, not openh264's:
124+ // `FF = round(F / MF)` reproduces our `(|c|·MF + F) >> qbits` (to within a rare ±1),
125+ // so RD is preserved AND the asm kernel becomes a drop-in. (Adopting openh264's own
126+ // FF tables regressed intra −1.5 dB.) `MF_oh[qp] = MF · 2^(16-qbits)`.
127+ let mf_oh = &QUANT_MF_OH[qp as usize];
128+ let ff = quant_dz_ff(qp, dz_div);
129+ const POS: [usize; 16] = [0, 1, 2, 3, 4, 5, 6, 7, 0, 1, 2, 3, 4, 5, 6, 7];
130+ let mut out = [0i32; 16];
131+ for idx in 0..16 {
132+ let p = POS[idx];
133+ let a = coeffs[idx].unsigned_abs() as i32;
134+ let lvl = ((a + ff[p] as i32) * mf_oh[p] as i32) >> 16;
135+ out[idx] = if coeffs[idx] < 0 { -lvl } else { lvl };
136+ }
137+ out
138+}
139+
140+/// The 8-entry deadzone offset table `FF[pos] = round(F / MF)` reproducing our
141+/// `(|c|·MF + F) >> qbits` deadzone (`F = 2^qbits / dz_div`) inside openh264's
142+/// `((|c| + FF)·MF_oh) >> 16` quantizer — so the asm `WelsQuant*4x4` kernels quantize
143+/// bit-identically to our scalar [`quantize`]. Pair with [`QUANT_MF_OH`]`[qp]` as MF.
144+pub fn quant_dz_ff(qp: u8, dz_div: i64) -> [i16; 8] {
145+ let m = (qp % 6) as usize;
146+ let qbits = 15 + (qp / 6) as i64;
147+ let f = (1i64 << qbits) / dz_div;
148+ // Position (0:even/even, 1:odd/odd, 2:mixed) group of each of openh264's 8 slots.
149+ const GROUP8: [usize; 8] = [0, 2, 0, 2, 2, 1, 2, 1];
150+ let mut ff = [0i16; 8];
151+ for (i, slot) in ff.iter_mut().enumerate() {
152+ let mfg = QUANT_MF[m][GROUP8[i]] as i64;
153+ *slot = ((f + mfg / 2) / mfg) as i16;
154+ }
155+ ff
156+}
157+
158+/// Rate-distortion–optimized ("trellis") quantization of a 4×4 residual's
159+/// transform coefficients. For each coefficient it chooses between the scalar
160+/// level and one lower (down to zero) to minimize `J = distortion + λ·rate`,
161+/// trading a few bits of coefficient coding for small reconstruction error.
162+/// `lambda` is the mode-decision Lagrangian (pixel-SSD domain). Encoder-only —
163+/// the output is still a valid set of levels any decoder reconstructs.
164+///
165+/// NOTE: not wired into the encoder by default. Greedy per-coefficient rounding
166+/// fights the intra-prediction feedback loop (rounding one block down worsens
167+/// the next block's prediction), so a net win needs a feedback-aware integration
168+/// — left as future work. Kept here as a verified building block.
169+pub fn trellis_quant(coeffs: &[i32; 16], qp: u8, intra: bool, lambda: f64) -> [i32; 16] {
170+ let m = (qp % 6) as usize;
171+ let qbits = 15 + (qp / 6) as u32;
172+ let scale = (1u64 << qbits) as f64;
173+ let off: i64 = if intra { (1i64 << qbits) / 3 } else { (1i64 << qbits) / 6 };
174+ let mut out = [0i32; 16];
175+ for i in 0..4 {
176+ for j in 0..4 {
177+ let idx = i * 4 + j;
178+ let w = coeffs[idx] as i64;
179+ let mf = QUANT_MF[m][pos_group(i, j)] as i64;
180+ let num = w.abs() * mf; // == ideal_level * 2^qbits
181+ let l_scalar = (num + off) >> qbits;
182+ if l_scalar == 0 {
183+ continue;
184+ }
185+ // Distortion is in level² units; convert λ (pixel-SSD) into that
186+ // domain via the dequant step (step ≈ 2^qbits / mf, pixel ≈ step/8).
187+ let lambda_q = lambda * (mf * mf) as f64 / (scale * scale) * 64.0;
188+ let ideal = num as f64 / scale;
189+ let mut best = l_scalar;
190+ let mut best_j = f64::MAX;
191+ for cand in [l_scalar - 1, l_scalar] {
192+ let d = (ideal - cand as f64).powi(2);
193+ let r = if cand == 0 {
194+ 0.0
195+ } else {
196+ // ~bits to code |level|: significance + sign + magnitude.
197+ 2.0 + 2.0 * (64 - (cand as u64).leading_zeros()) as f64
198+ };
199+ let jj = d + lambda_q * r;
200+ if jj < best_j {
201+ best_j = jj;
202+ best = cand;
203+ }
204+ }
205+ out[idx] = if w < 0 { -best as i32 } else { best as i32 };
206+ }
207+ }
208+ out
209+}
210+
211+/// Dequantizes levels to scaled coefficients (spec §8.5.12.1, flat scaling
212+/// list so `LevelScale = 16 · normAdjust`).
213+/// OPT-IN SWITCH — `RS_H264_DEQUANT_AVX2=1` enables the AVX2 twin, which measured NULL
214+/// (8/13 favouring scalar, z = 0.83). Both arms live in one binary so the A/B runs under
215+/// one thermal state; separate builds cannot resolve an effect this size here.
216+#[cfg(all(target_arch = "x86_64", feature = "asm"))]
217+#[inline]
218+fn dequant_avx2_opt_in() -> bool {
219+ use std::sync::atomic::{AtomicU8, Ordering};
220+ static ON: AtomicU8 = AtomicU8::new(0);
221+ match ON.load(Ordering::Relaxed) {
222+ 1 => true,
223+ 2 => false,
224+ _ => {
225+ let on = std::env::var_os("RS_H264_DEQUANT_AVX2").is_some_and(|v| v != "0");
226+ ON.store(if on { 1 } else { 2 }, Ordering::Relaxed);
227+ on
228+ }
229+ }
230+}
231+
232+pub fn dequantize(levels: &[i32; 16], qp: u8) -> [i32; 16] {
233+ let _g = crate::prof::scope(crate::prof::Stage::Dequant);
234+ let m = (qp % 6) as usize;
235+ let shift = (qp / 6) as i32;
236+ let ls = &LEVEL_SCALE_FLAT[m];
237+ let mut out = [0i32; 16];
238+ // AVX2 twin: 16 scalar `imul` -> 2 `vpmulld`. Bit-identical (exact integer ops in
239+ // the same order), so the scalar body below stays as the oracle AND as the path on
240+ // any non-AVX2 CPU. See `dequant_4x4_avx2` for why auto-vectorization does not
241+ // reach this loop.
242+ // DEFAULT: SCALAR. The AVX2 twin is opt-IN (`RS_H264_DEQUANT_AVX2=1`).
243+ //
244+ // MEASURED NULL, leaning negative: 13 pairs, pinned, CPU time, ABBA, against a null
245+ // arm of 0.989 taken in the same session — the SCALAR arm was faster in 8/13
246+ // (z = 0.83, not significant either way). The kernel provably removes 8x the
247+ // multiply instructions (776M `imul` -> 97M `vpmulld`, confirmed in the asm) and
248+ // that bought NOTHING.
249+ //
250+ // Why: dequant loads 16 levels + 16 scale factors and stores 16 outputs — 192 bytes
251+ // per call. It is MEMORY-bound, so the scalar `imul`s were already hidden under the
252+ // loads. Widening the arithmetic cannot help a loop whose clock is set by traffic.
253+ // This is the same law that reverted three earlier bricks in this campaign: a
254+ // counter proves work was REMOVED, never that time was SAVED.
255+ //
256+ // Kept in tree (byte-identical, bit-exact-gated) because it costs nothing to keep
257+ // and re-testing is one env var if the surrounding loads ever shrink.
258+ #[cfg(all(target_arch = "x86_64", feature = "asm"))]
259+ if dequant_avx2_opt_in() && rusty_h264_accel::dequant_4x4(&mut out, levels, ls, qp) {
260+ return out;
261+ }
262+ if qp >= 24 {
263+ let sh = shift - 4;
264+ for idx in 0..16 {
265+ out[idx] = (levels[idx] * ls[idx]) << sh;
266+ }
267+ } else {
268+ let add = 1 << (3 - shift);
269+ let sh = 4 - shift;
270+ for idx in 0..16 {
271+ out[idx] = (levels[idx] * ls[idx] + add) >> sh;
272+ }
273+ }
274+ out
275+}
276+
277+/// 4×4 zig-zag: scan position → raster position (spec Table 8-13; the inverse
278+/// of the `un_scan_4x4_dcac` mapping in `cavlc.rs`).
279+pub const ZIG4: [usize; 16] = [0, 1, 4, 8, 5, 2, 3, 6, 9, 12, 13, 10, 7, 11, 14, 15];
280+
281+/// Fused un-scan + dequant that touches ONLY the significant coefficients.
282+///
283+/// Bit-exact with `dequantize(&un_scan(scan))` / the weighted twin: a zero
284+/// level dequantizes to zero under both branches (for qp<24,
285+/// `(0·ls + (1<<(3-shift))) >> (4-shift)` is 0 for every shift 0..=3), so
286+/// skipping the zeros IS the dense computation. `nnz` is the parse's count of
287+/// significant coefficients (exact — CABAC levels are never zero), so the loop
288+/// exits after the LAST significant coefficient instead of walking all 16:
289+/// dense un-scan (16 loads+stores) + dense dequant (16 multiplies) become
290+/// `nnz` multiplies scattered directly to raster order.
291+///
292+/// `ac_shift` selects the category's scan base: 0 for a full DC+AC block,
293+/// 1 for an AC-only block (chroma AC), whose scan index `i` is overall scan
294+/// position `i + 1`.
295+#[inline]
296+pub fn dequant_scatter_4x4(
297+ scan: &[i32; 16],
298+ nnz: u8,
299+ ac_shift: usize,
300+ qp: u8,
301+ weight: Option<&[i32; 16]>,
302+) -> [i32; 16] {
303+ let _g = crate::prof::scope(crate::prof::Stage::Dequant);
304+ let m = (qp % 6) as usize;
305+ let shift = (qp / 6) as i32;
306+ let mut out = [0i32; 16];
307+ let mut seen = 0u8;
308+ let mut i = 0usize;
309+ while seen < nnz && i + ac_shift < 16 {
310+ let v = scan[i];
311+ if v != 0 {
312+ let pos = ZIG4[i + ac_shift];
313+ let ls = match weight {
314+ Some(w) => w[pos] * NORM_ADJUST[m][POS_GROUP_FLAT[pos]],
315+ None => LEVEL_SCALE_FLAT[m][pos],
316+ };
317+ out[pos] = if qp >= 24 {
318+ (v * ls) << (shift - 4)
319+ } else {
320+ (v * ls + (1 << (3 - shift))) >> (4 - shift)
321+ };
322+ seen += 1;
323+ }
324+ i += 1;
325+ }
326+ out
327+}
328+
329+/// Dequantizes ONLY position 0 of a 4×4 block — the single-coefficient twin of
330+/// [`dequantize`] / [`dequantize_weighted`], bit-exact with their `out[0]`.
331+///
332+/// Exists for the DC-ONLY fast path: when a block's sole significant
333+/// coefficient is the DC, `inverse_core` provably flattens to `(f + 32) >> 6`
334+/// at every position (row pass spreads f across row 0, column pass across all
335+/// rows, and each `inv_1d` of `(f,0,0,0)` is exact — no `>> 1` flooring path is
336+/// taken), so the full 16-multiply dequant + two butterfly passes reduce to
337+/// this one multiply. This is ffmpeg's `h264_idct_dc_add` split, arrived at
338+/// from the fusion diagnosis (WHYS Part 8).
339+#[inline]
340+pub fn dequantize_dc4(level: i32, qp: u8, weight0: Option<i32>) -> i32 {
341+ let m = (qp % 6) as usize;
342+ let shift = (qp / 6) as i32;
343+ let ls0 = match weight0 {
344+ Some(w) => w * NORM_ADJUST[m][POS_GROUP_FLAT[0]],
345+ None => LEVEL_SCALE_FLAT[m][0],
346+ };
347+ if qp >= 24 {
348+ (level * ls0) << (shift - 4)
349+ } else {
350+ (level * ls0 + (1 << (3 - shift))) >> (4 - shift)
351+ }
352+}
353+
354+/// Dequantizes with a per-position weight scale (`weightScale4x4` in raster order,
355+/// `16` = flat) — High-profile scaling matrices (spec §8.5.12.1,
356+/// `LevelScale = weightScale · normAdjust`).
357+pub fn dequantize_weighted(levels: &[i32; 16], qp: u8, weight: &[i32; 16]) -> [i32; 16] {
358+ let _g = crate::prof::scope(crate::prof::Stage::Dequant);
359+ let m = (qp % 6) as usize;
360+ let shift = (qp / 6) as i32;
361+ let ls: [i32; 16] = std::array::from_fn(|idx| weight[idx] * NORM_ADJUST[m][POS_GROUP_FLAT[idx]]);
362+ let mut out = [0i32; 16];
363+ if qp >= 24 {
364+ let sh = shift - 4;
365+ for idx in 0..16 {
366+ out[idx] = (levels[idx] * ls[idx]) << sh;
367+ }
368+ } else {
369+ let add = 1 << (3 - shift);
370+ let sh = 4 - shift;
371+ for idx in 0..16 {
372+ out[idx] = (levels[idx] * ls[idx] + add) >> sh;
373+ }
374+ }
375+ out
376+}
377+
378+/// Inverse core transform + final normalization, turning dequantized
379+/// coefficients back into a residual block (spec §8.5.12.2: `(f + 32) >> 6`).
380+pub fn inverse_core(coeffs: &[i32; 16]) -> [i32; 16] {
381+ let mut m = *coeffs;
382+ // Rows first, then columns. The order is **not** interchangeable: the
383+ // `>> 1` flooring inside `inv_1d` makes the integer transform non-separable,
384+ // so the spec (§8.5.12.2 — horizontal row transform, then vertical) and the
385+ // decoder must agree exactly. (A column-first pass diverges by ±1 on
386+ // asymmetric blocks, which only surfaces at low QP / high-frequency content.)
387+ for r in 0..4 {
388+ let (a, b, c, d) = inv_1d(m[r * 4], m[r * 4 + 1], m[r * 4 + 2], m[r * 4 + 3]);
389+ m[r * 4] = a;
390+ m[r * 4 + 1] = b;
391+ m[r * 4 + 2] = c;
392+ m[r * 4 + 3] = d;
393+ }
394+ for c in 0..4 {
395+ let (a, b, cc, d) = inv_1d(m[c], m[4 + c], m[8 + c], m[12 + c]);
396+ m[c] = a;
397+ m[4 + c] = b;
398+ m[8 + c] = cc;
399+ m[12 + c] = d;
400+ }
401+ for v in m.iter_mut() {
402+ *v = (*v + 32) >> 6;
403+ }
404+ m
405+}
406+
407+/// Convenience: full forward path, residual → quantized levels (default
408+/// dead-zones: 3 for intra, 6 for inter).
409+pub fn forward_quant(residual: &[i32; 16], qp: u8, intra: bool) -> [i32; 16] {
410+ quantize(&forward_core(residual), qp, if intra { 3 } else { 6 })
411+}
412+
413+/// Convenience: full inverse path, quantized levels → reconstructed residual.
414+pub fn inverse_quant(levels: &[i32; 16], qp: u8) -> [i32; 16] {
415+ inverse_core(&dequantize(levels, qp))
416+}
417+
418+// ---- 8×8 transform (High profile, spec §8.5.13) ----
419+
420+/// `normAdjust8x8` (spec Table 8-15), indexed by `[QP % 6]` then 8×8 position
421+/// group (see [`pos_group_8x8`]).
422+const NORM_ADJUST_8X8: [[i32; 6]; 6] = [
423+ [20, 18, 32, 19, 25, 24],
424+ [22, 19, 35, 21, 28, 26],
425+ [26, 23, 42, 24, 33, 31],
426+ [28, 25, 45, 26, 35, 33],
427+ [32, 28, 51, 30, 40, 38],
428+ [36, 32, 58, 34, 46, 43],
429+];
430+
431+/// Position group of `(i, j)` within an 8×8 block (spec §8.5.13.1) — six groups
432+/// vs the 4×4's three.
433+#[inline]
434+const fn pos_group_8x8(i: usize, j: usize) -> usize {
435+ let (i4, j4) = (i % 4, j % 4);
436+ if i4 == 0 && j4 == 0 {
437+ 0
438+ } else if i % 2 == 1 && j % 2 == 1 {
439+ 1
440+ } else if i4 == 2 && j4 == 2 {
441+ 2
442+ } else if (i4 == 0 && j % 2 == 1) || (i % 2 == 1 && j4 == 0) {
443+ 3
444+ } else if (i4 == 0 && j4 == 2) || (i4 == 2 && j4 == 0) {
445+ 4
446+ } else {
447+ 5
448+ }
449+}
450+
451+/// `pos_group_8x8` flattened over the 64 raster positions.
452+const POS_GROUP_8X8_FLAT: [usize; 64] = {
453+ let mut out = [0usize; 64];
454+ let mut i = 0;
455+ while i < 8 {
456+ let mut j = 0;
457+ while j < 8 {
458+ out[i * 8 + j] = pos_group_8x8(i, j);
459+ j += 1;
460+ }
461+ i += 1;
462+ }
463+ out
464+};
465+
466+/// One-dimensional inverse 8×8 transform (spec §8.5.13.2 butterfly).
467+#[inline]
468+fn inv_1d_8x8(d: &[i32; 8]) -> [i32; 8] {
469+ let a0 = d[0] + d[4];
470+ let a4 = d[0] - d[4];
471+ let a2 = (d[2] >> 1) - d[6];
472+ let a6 = d[2] + (d[6] >> 1);
473+ let b0 = a0 + a6;
474+ let b2 = a4 + a2;
475+ let b4 = a4 - a2;
476+ let b6 = a0 - a6;
477+ let a1 = -d[3] + d[5] - d[7] - (d[7] >> 1);
478+ let a3 = d[1] + d[7] - d[3] - (d[3] >> 1);
479+ let a5 = -d[1] + d[7] + d[5] + (d[5] >> 1);
480+ let a7 = d[3] + d[5] + d[1] + (d[1] >> 1);
481+ let b1 = a1 + (a7 >> 2);
482+ let b7 = a7 - (a1 >> 2);
483+ let b3 = a3 + (a5 >> 2);
484+ let b5 = (a3 >> 2) - a5;
485+ [b0 + b7, b2 + b5, b4 + b3, b6 + b1, b6 - b1, b4 - b3, b2 - b5, b0 - b7]
486+}
487+
488+/// One-dimensional forward 8×8 transform — the matched pair of [`inv_1d_8x8`]
489+/// (the ENCODER's forward transform for the High-profile 8×8 residual).
490+#[inline]
491+fn fwd_1d_8x8(s: &[i32; 8]) -> [i32; 8] {
492+ let a0 = s[0] + s[7];
493+ let a1 = s[1] + s[6];
494+ let a2 = s[2] + s[5];
495+ let a3 = s[3] + s[4];
496+ let a4 = s[0] - s[7];
497+ let a5 = s[1] - s[6];
498+ let a6 = s[2] - s[5];
499+ let a7 = s[3] - s[4];
500+ let b0 = a0 + a3;
501+ let b1 = a1 + a2;
502+ let b2 = a0 - a3;
503+ let b3 = a1 - a2;
504+ let y0 = b0 + b1;
505+ let y2 = b2 + (b3 >> 1);
506+ let y4 = b0 - b1;
507+ let y6 = (b2 >> 1) - b3;
508+ let b4 = a5 + a6 + ((a4 >> 1) + a4);
509+ let b5 = a4 - a7 - ((a6 >> 1) + a6);
510+ let b6 = a4 + a7 - ((a5 >> 1) + a5);
511+ let b7 = a5 - a6 + ((a7 >> 1) + a7);
512+ let y1 = b4 + (b7 >> 2);
513+ let y3 = b5 + (b6 >> 2);
514+ let y5 = b6 - (b5 >> 2);
515+ let y7 = (b4 >> 2) - b7;
516+ [y0, y1, y2, y3, y4, y5, y6, y7]
517+}
518+
519+/// Inverse 8×8 core transform + normalization (`(x + 32) >> 6`), rows then
520+/// columns (non-separable, like the 4×4 — the order is fixed by the spec).
521+pub fn inverse_core_8x8(coeffs: &[i32; 64]) -> [i32; 64] {
522+ let _g = crate::prof::scope(crate::prof::Stage::Reconstruct);
523+ let mut m = *coeffs;
524+ for r in 0..8 {
525+ let row: [i32; 8] = std::array::from_fn(|k| m[r * 8 + k]);
526+ let o = inv_1d_8x8(&row);
527+ for k in 0..8 {
528+ m[r * 8 + k] = o[k];
529+ }
530+ }
531+ for c in 0..8 {
532+ let col: [i32; 8] = std::array::from_fn(|k| m[k * 8 + c]);
533+ let o = inv_1d_8x8(&col);
534+ for k in 0..8 {
535+ m[k * 8 + c] = o[k];
536+ }
537+ }
538+ for v in m.iter_mut() {
539+ *v = (*v + 32) >> 6;
540+ }
541+ m
542+}
543+
544+/// Forward 8×8 core transform (rows then columns) — the encoder counterpart of
545+/// [`inverse_core_8x8`]. Output are un-normalized transform coefficients for
546+/// [`quantize_8x8`]; the normalization lives in the quant/dequant scale.
547+pub fn forward_core_8x8(res: &[i32; 64]) -> [i32; 64] {
548+ let mut m = *res;
549+ for r in 0..8 {
550+ let row: [i32; 8] = std::array::from_fn(|k| m[r * 8 + k]);
551+ let o = fwd_1d_8x8(&row);
552+ for k in 0..8 {
553+ m[r * 8 + k] = o[k];
554+ }
555+ }
556+ for c in 0..8 {
557+ let col: [i32; 8] = std::array::from_fn(|k| m[k * 8 + c]);
558+ let o = fwd_1d_8x8(&col);
559+ for k in 0..8 {
560+ m[k * 8 + c] = o[k];
561+ }
562+ }
563+ m
564+}
565+
566+/// Dequantizes an 8×8 block (spec §8.5.13.1) with a per-position `weight` scale
567+/// (raster order, `16` = flat). `LevelScale8x8 = weight · normAdjust8x8`.
568+pub fn dequantize_8x8(levels: &[i32; 64], qp: u8, weight: &[i32; 64]) -> [i32; 64] {
569+ let _g = crate::prof::scope(crate::prof::Stage::Dequant);
570+ let m = (qp % 6) as usize;
571+ let shift = (qp / 6) as i32;
572+ let mut out = [0i32; 64];
573+ if qp >= 36 {
574+ let sh = shift - 6;
575+ for idx in 0..64 {
576+ let ls = weight[idx] * NORM_ADJUST_8X8[m][POS_GROUP_8X8_FLAT[idx]];
577+ out[idx] = (levels[idx] * ls) << sh;
578+ }
579+ } else {
580+ let add = 1 << (5 - shift);
581+ let sh = 6 - shift;
582+ for idx in 0..64 {
583+ let ls = weight[idx] * NORM_ADJUST_8X8[m][POS_GROUP_8X8_FLAT[idx]];
584+ out[idx] = (levels[idx] * ls + add) >> sh;
585+ }
586+ }
587+ out
588+}
589+
590+/// Convenience: full inverse 8×8 path, levels → reconstructed residual.
591+pub fn inverse_quant_8x8(levels: &[i32; 64], qp: u8, weight: &[i32; 64]) -> [i32; 64] {
592+ inverse_core_8x8(&dequantize_8x8(levels, qp, weight))
593+}
594+
595+/// 8×8 forward-quant multiplier `MF = round(2^18 / normAdjust8x8)` per `[QP%6]`
596+/// then position group. Chosen as the exact arithmetic inverse of
597+/// [`dequantize_8x8`]'s scale (`MF · weight · normAdjust ≈ 2^qbits`, qbits =
598+/// 16+QP/6, flat weight 16) so quant∘dequant round-trips near-identity.
599+const QUANT_MF_8X8: [[i32; 6]; 6] = [
600+ [13107, 14564, 8192, 13797, 10486, 10923],
601+ [11916, 13797, 7490, 12483, 9362, 10083],
602+ [10083, 11398, 6242, 10923, 7944, 8456],
603+ [9362, 10486, 5825, 10083, 7490, 7944],
604+ [8192, 9362, 5140, 8738, 6554, 6899],
605+ [7282, 8192, 4520, 7710, 5699, 6096],
606+];
607+
608+/// Forward-quantizes an 8×8 coefficient block (encoder). `level = (|c|·MF + F) >>
609+/// qbits`, qbits = 16+QP/6, deadzone `F = 2^qbits / dz_div` (like the 4×4 path).
610+/// `weight` is the per-position scaling-list value (raster; `16` = flat) — the
611+/// matched inverse of [`dequantize_8x8`], so `dequantize_8x8(quantize_8x8(c)) ≈ c`.
612+pub fn quantize_8x8(coeffs: &[i32; 64], qp: u8, weight: &[i32; 64], dz_div: i64) -> [i32; 64] {
613+ let m = (qp % 6) as usize;
614+ let qbits = 16 + (qp / 6) as i64;
615+ let ff = (1i64 << qbits) / dz_div;
616+ let mut out = [0i32; 64];
617+ for idx in 0..64 {
618+ let mf = QUANT_MF_8X8[m][POS_GROUP_8X8_FLAT[idx]] as i64 * 16 / weight[idx] as i64;
619+ let a = coeffs[idx].unsigned_abs() as i64;
620+ let lvl = ((a * mf + ff) >> qbits) as i32;
621+ out[idx] = if coeffs[idx] < 0 { -lvl } else { lvl };
622+ }
623+ out
624+}
625+
626+// ---- Secondary DC transforms for I_16x16 luma and chroma (Hadamard) ----
627+
628+/// In-place 1D 4-point Hadamard (its own inverse up to scale).
629+#[inline]
630+fn hadamard_1d(a: i32, b: i32, c: i32, d: i32) -> (i32, i32, i32, i32) {
631+ (a + b + c + d, a + b - c - d, a - b - c + d, a - b + c - d)
632+}
633+
634+/// 4×4 Hadamard transform (rows then columns), used for the I_16x16 luma DC
635+/// block. Symmetric, so the same routine serves forward and inverse.
636+pub fn hadamard_4x4(block: &[i32; 16]) -> [i32; 16] {
637+ let mut m = *block;
638+ for r in 0..4 {
639+ let (a, b, c, d) = hadamard_1d(m[r * 4], m[r * 4 + 1], m[r * 4 + 2], m[r * 4 + 3]);
640+ m[r * 4] = a;
641+ m[r * 4 + 1] = b;
642+ m[r * 4 + 2] = c;
643+ m[r * 4 + 3] = d;
644+ }
645+ for c in 0..4 {
646+ let (a, b, cc, d) = hadamard_1d(m[c], m[4 + c], m[8 + c], m[12 + c]);
647+ m[c] = a;
648+ m[4 + c] = b;
649+ m[8 + c] = cc;
650+ m[12 + c] = d;
651+ }
652+ m
653+}
654+
655+/// 4-point Hadamard butterfly applied lane-wise across four SIMD vectors. Same
656+/// `(a+b+c+d, a+b-c-d, a-b-c+d, a-b+c-d)` as the scalar [`hadamard_1d`].
657+#[inline]
658+fn had4_simd(
659+ a: wide::i32x4,
660+ b: wide::i32x4,
661+ c: wide::i32x4,
662+ d: wide::i32x4,
663+) -> (wide::i32x4, wide::i32x4, wide::i32x4, wide::i32x4) {
664+ (a + b + c + d, a + b - c - d, a - b - c + d, a - b + c - d)
665+}
666+
667+/// SATD of exactly four 4×4 residual blocks at once, summed. Each block lives in
668+/// its own SIMD lane, so the position-within-block dimension runs across the
669+/// array of vectors — both Hadamard passes become plain across-vector butterflies
670+/// with no transpose. Bit-identical to summing `Σ|hadamard_4x4(res)|` per block.
671+fn satd_4x4_x4(b: [&[i32; 16]; 4]) -> i64 {
672+ use wide::i32x4;
673+ // v[p] holds position `p` of all four blocks (lane k = block k).
674+ let mut v = [i32x4::from([0i32; 4]); 16];
675+ for (p, slot) in v.iter_mut().enumerate() {
676+ *slot = i32x4::from([b[0][p], b[1][p], b[2][p], b[3][p]]);
677+ }
678+ // Row transform: combine the four positions within each row.
679+ for r in 0..4 {
680+ let i = r * 4;
681+ let (a, c, d, e) = had4_simd(v[i], v[i + 1], v[i + 2], v[i + 3]);
682+ (v[i], v[i + 1], v[i + 2], v[i + 3]) = (a, c, d, e);
683+ }
684+ // Column transform: combine the four rows at each column.
685+ for c in 0..4 {
686+ let (a, b2, d, e) = had4_simd(v[c], v[c + 4], v[c + 8], v[c + 12]);
687+ (v[c], v[c + 4], v[c + 8], v[c + 12]) = (a, b2, d, e);
688+ }
689+ // Σ|coeff|, lane-wise (|x| = max(0,x) − min(0,x)), then sum the four lanes.
690+ let zero = i32x4::from([0i32; 4]);
691+ let mut acc = zero;
692+ for x in v {
693+ acc += zero.max(x) - zero.min(x);
694+ }
695+ acc.to_array().iter().map(|&s| s as i64).sum()
696+}
697+
698+/// SATD over a slice of 4×4 residual blocks (SIMD four at a time, scalar tail).
699+/// This is the cost kernel for motion estimation and RD mode decision.
700+pub fn satd_4x4_sum(blocks: &[[i32; 16]]) -> i64 {
701+ let mut total = 0i64;
702+ let mut chunks = blocks.chunks_exact(4);
703+ for g in &mut chunks {
704+ total += satd_4x4_x4([&g[0], &g[1], &g[2], &g[3]]);
705+ }
706+ for res in chunks.remainder() {
707+ total += hadamard_4x4(res).iter().map(|&v| v.unsigned_abs() as i64).sum::<i64>();
708+ }
709+ total
710+}
711+
712+/// Forward core 1-D butterfly applied lane-wise across four SIMD vectors. Same
713+/// `(t0+t1, 2·t3+t2, t0-t1, t3-2·t2)` as the scalar [`fwd_1d`].
714+#[inline]
715+fn fwd_1d_simd(
716+ x0: wide::i32x4,
717+ x1: wide::i32x4,
718+ x2: wide::i32x4,
719+ x3: wide::i32x4,
720+) -> (wide::i32x4, wide::i32x4, wide::i32x4, wide::i32x4) {
721+ let t0 = x0 + x3;
722+ let t1 = x1 + x2;
723+ let t2 = x1 - x2;
724+ let t3 = x0 - x3;
725+ (t0 + t1, (t3 + t3) + t2, t0 - t1, t3 - (t2 + t2))
726+}
727+
728+/// Forward core 4×4 transform of four blocks at once — each block in its own SIMD
729+/// lane, so both passes are across-vector butterflies (no transpose), exactly like
730+/// [`satd_4x4_sum`]. Integer math ⇒ bit-identical to four [`forward_core`] calls.
731+fn forward_core_x4(b: [&[i32; 16]; 4]) -> [[i32; 16]; 4] {
732+ use wide::i32x4;
733+ let mut v = [i32x4::from([0i32; 4]); 16];
734+ for (p, slot) in v.iter_mut().enumerate() {
735+ *slot = i32x4::from([b[0][p], b[1][p], b[2][p], b[3][p]]);
736+ }
737+ for r in 0..4 {
738+ let i = r * 4;
739+ let (a, c, d, e) = fwd_1d_simd(v[i], v[i + 1], v[i + 2], v[i + 3]);
740+ (v[i], v[i + 1], v[i + 2], v[i + 3]) = (a, c, d, e);
741+ }
742+ for c in 0..4 {
743+ let (a, b2, d, e) = fwd_1d_simd(v[c], v[c + 4], v[c + 8], v[c + 12]);
744+ (v[c], v[c + 4], v[c + 8], v[c + 12]) = (a, b2, d, e);
745+ }
746+ let mut out = [[0i32; 16]; 4];
747+ for (p, vp) in v.iter().enumerate() {
748+ let a = vp.to_array();
749+ for k in 0..4 {
750+ out[k][p] = a[k];
751+ }
752+ }
753+ out
754+}
755+
756+/// `i32x8` (AVX2-width, 8 blocks/lane) sibling of [`fwd_1d_simd`] — mirrors the
757+/// width of x264's AVX2 DCT kernels. (Realizes AVX2 only under a CPU-targeted
758+/// build/dispatch; on the portable SSE2 build it is two `i32x4` ops.)
759+#[inline]
760+fn fwd_1d_simd8(
761+ x0: wide::i32x8,
762+ x1: wide::i32x8,
763+ x2: wide::i32x8,
764+ x3: wide::i32x8,
765+) -> (wide::i32x8, wide::i32x8, wide::i32x8, wide::i32x8) {
766+ let t0 = x0 + x3;
767+ let t1 = x1 + x2;
768+ let t2 = x1 - x2;
769+ let t3 = x0 - x3;
770+ (t0 + t1, (t3 + t3) + t2, t0 - t1, t3 - (t2 + t2))
771+}
772+
773+/// Forward core 4×4 transform of EIGHT blocks at once (8-wide `i32x8`, AVX2
774+/// kernel width). Bit-identical to eight [`forward_core`] calls.
775+fn forward_core_x8(b: [&[i32; 16]; 8]) -> [[i32; 16]; 8] {
776+ use wide::i32x8;
777+ let mut v = [i32x8::from([0i32; 8]); 16];
778+ for (p, slot) in v.iter_mut().enumerate() {
779+ *slot = i32x8::from([
780+ b[0][p], b[1][p], b[2][p], b[3][p], b[4][p], b[5][p], b[6][p], b[7][p],
781+ ]);
782+ }
783+ for r in 0..4 {
784+ let i = r * 4;
785+ let (a, c, d, e) = fwd_1d_simd8(v[i], v[i + 1], v[i + 2], v[i + 3]);
786+ (v[i], v[i + 1], v[i + 2], v[i + 3]) = (a, c, d, e);
787+ }
788+ for c in 0..4 {
789+ let (a, b2, d, e) = fwd_1d_simd8(v[c], v[c + 4], v[c + 8], v[c + 12]);
790+ (v[c], v[c + 4], v[c + 8], v[c + 12]) = (a, b2, d, e);
791+ }
792+ let mut out = [[0i32; 16]; 8];
793+ for (p, vp) in v.iter().enumerate() {
794+ let a = vp.to_array();
795+ for k in 0..8 {
796+ out[k][p] = a[k];
797+ }
798+ }
799+ out
800+}
801+
802+/// Forward core transform over a batch of 4×4 residual blocks — the encoder's
803+/// whole-macroblock DCT, mirroring x264's `sub16x16_dct`. SIMD eight at a time
804+/// (`i32x8`, AVX2 width), then four (`i32x4`), then a scalar tail.
805+pub fn forward_dct_blocks(res: &[[i32; 16]], out: &mut [[i32; 16]]) {
806+ let mut i = 0;
807+ let mut c8 = res.chunks_exact(8);
808+ for g in &mut c8 {
809+ let r = forward_core_x8([&g[0], &g[1], &g[2], &g[3], &g[4], &g[5], &g[6], &g[7]]);
810+ out[i..i + 8].clone_from_slice(&r);
811+ i += 8;
812+ }
813+ let mut c4 = c8.remainder().chunks_exact(4);
814+ for g in &mut c4 {
815+ let r = forward_core_x4([&g[0], &g[1], &g[2], &g[3]]);
816+ out[i..i + 4].clone_from_slice(&r);
817+ i += 4;
818+ }
819+ for r in c4.remainder() {
820+ out[i] = forward_core(r);
821+ i += 1;
822+ }
823+}
824+
825+/// Inverse core 1-D butterfly applied lane-wise across four SIMD vectors. Same
826+/// `(e0+e3, e1+e2, e1-e2, e0-e3)` as the scalar [`inv_1d`] (per-lane arithmetic
827+/// `>> 1`, so bit-identical).
828+#[inline]
829+fn inv_1d_simd(
830+ d0: wide::i32x4,
831+ d1: wide::i32x4,
832+ d2: wide::i32x4,
833+ d3: wide::i32x4,
834+) -> (wide::i32x4, wide::i32x4, wide::i32x4, wide::i32x4) {
835+ let e0 = d0 + d2;
836+ let e1 = d0 - d2;
837+ let e2 = (d1 >> 1) - d3;
838+ let e3 = d1 + (d3 >> 1);
839+ (e0 + e3, e1 + e2, e1 - e2, e0 - e3)
840+}
841+
842+/// Inverse core 4×4 transform + `(f + 32) >> 6` normalization of four blocks at
843+/// once — each block in its own SIMD lane. Bit-identical to four [`inverse_core`].
844+fn inverse_core_x4(b: [&[i32; 16]; 4]) -> [[i32; 16]; 4] {
845+ use wide::i32x4;
846+ let mut v = [i32x4::from([0i32; 4]); 16];
847+ for (p, slot) in v.iter_mut().enumerate() {
848+ *slot = i32x4::from([b[0][p], b[1][p], b[2][p], b[3][p]]);
849+ }
850+ for r in 0..4 {
851+ let i = r * 4;
852+ let (a, c, d, e) = inv_1d_simd(v[i], v[i + 1], v[i + 2], v[i + 3]);
853+ (v[i], v[i + 1], v[i + 2], v[i + 3]) = (a, c, d, e);
854+ }
855+ for c in 0..4 {
856+ let (a, b2, d, e) = inv_1d_simd(v[c], v[c + 4], v[c + 8], v[c + 12]);
857+ (v[c], v[c + 4], v[c + 8], v[c + 12]) = (a, b2, d, e);
858+ }
859+ let off = i32x4::from([32i32; 4]);
860+ for vp in v.iter_mut() {
861+ *vp = (*vp + off) >> 6;
862+ }
863+ let mut out = [[0i32; 16]; 4];
864+ for (p, vp) in v.iter().enumerate() {
865+ let a = vp.to_array();
866+ for k in 0..4 {
867+ out[k][p] = a[k];
868+ }
869+ }
870+ out
871+}
872+
873+/// `i32x8` (AVX2-width) sibling of [`inv_1d_simd`].
874+#[inline]
875+fn inv_1d_simd8(
876+ d0: wide::i32x8,
877+ d1: wide::i32x8,
878+ d2: wide::i32x8,
879+ d3: wide::i32x8,
880+) -> (wide::i32x8, wide::i32x8, wide::i32x8, wide::i32x8) {
881+ let e0 = d0 + d2;
882+ let e1 = d0 - d2;
883+ let e2 = (d1 >> 1) - d3;
884+ let e3 = d1 + (d3 >> 1);
885+ (e0 + e3, e1 + e2, e1 - e2, e0 - e3)
886+}
887+
888+/// Inverse core 4×4 transform + normalization of EIGHT blocks at once (`i32x8`).
889+/// Bit-identical to eight [`inverse_core`] calls.
890+fn inverse_core_x8(b: [&[i32; 16]; 8]) -> [[i32; 16]; 8] {
891+ use wide::i32x8;
892+ let mut v = [i32x8::from([0i32; 8]); 16];
893+ for (p, slot) in v.iter_mut().enumerate() {
894+ *slot = i32x8::from([
895+ b[0][p], b[1][p], b[2][p], b[3][p], b[4][p], b[5][p], b[6][p], b[7][p],
896+ ]);
897+ }
898+ for r in 0..4 {
899+ let i = r * 4;
900+ let (a, c, d, e) = inv_1d_simd8(v[i], v[i + 1], v[i + 2], v[i + 3]);
901+ (v[i], v[i + 1], v[i + 2], v[i + 3]) = (a, c, d, e);
902+ }
903+ for c in 0..4 {
904+ let (a, b2, d, e) = inv_1d_simd8(v[c], v[c + 4], v[c + 8], v[c + 12]);
905+ (v[c], v[c + 4], v[c + 8], v[c + 12]) = (a, b2, d, e);
906+ }
907+ let off = i32x8::from([32i32; 8]);
908+ for vp in v.iter_mut() {
909+ *vp = (*vp + off) >> 6;
910+ }
911+ let mut out = [[0i32; 16]; 8];
912+ for (p, vp) in v.iter().enumerate() {
913+ let a = vp.to_array();
914+ for k in 0..8 {
915+ out[k][p] = a[k];
916+ }
917+ }
918+ out
919+}
920+
921+/// Inverse core transform + normalization over a batch of dequantized 4×4 blocks
922+/// — the whole-macroblock IDCT, mirroring x264's `add16x16_idct`. SIMD eight at a
923+/// time (`i32x8`), then four (`i32x4`), then a scalar tail. Bit-identical to
924+/// [`inverse_core`] per block. (Add-prediction + clip stays per-block at the call
925+/// site, where the prediction layout lives.)
926+pub fn inverse_dct_blocks(coeffs: &[[i32; 16]], out: &mut [[i32; 16]]) {
927+ let mut i = 0;
928+ let mut c8 = coeffs.chunks_exact(8);
929+ for g in &mut c8 {
930+ let r = inverse_core_x8([&g[0], &g[1], &g[2], &g[3], &g[4], &g[5], &g[6], &g[7]]);
931+ out[i..i + 8].clone_from_slice(&r);
932+ i += 8;
933+ }
934+ let mut c4 = c8.remainder().chunks_exact(4);
935+ for g in &mut c4 {
936+ let r = inverse_core_x4([&g[0], &g[1], &g[2], &g[3]]);
937+ out[i..i + 4].clone_from_slice(&r);
938+ i += 4;
939+ }
940+ for r in c4.remainder() {
941+ out[i] = inverse_core(r);
942+ i += 1;
943+ }
944+}
945+
946+
947+/// Forward transform + quantization of the 16 luma DC coefficients of an
948+/// I_16x16 macroblock (spec §8.5.10). Input/output are row-major 4×4.
949+pub fn forward_quant_luma_dc(dc: &[i32; 16], qp: u8, intra: bool) -> [i32; 16] {
950+ let f = hadamard_4x4(dc);
951+ let m = (qp % 6) as usize;
952+ // The 4×4 Hadamard has gain 16 (its square is 16·I), so the luma DC quant
953+ // carries two extra bits over the AC quant to keep the reconstructed DC at
954+ // the same scale as the regular dequantized DC coefficient.
955+ let qbits = 17 + (qp / 6) as u32;
956+ let off: i64 = if intra { (1i64 << qbits) / 3 } else { (1i64 << qbits) / 6 };
957+ let mf = QUANT_MF[m][0] as i64;
958+ let mut out = [0i32; 16];
959+ for (o, &fv) in out.iter_mut().zip(f.iter()) {
960+ let level = ((fv.abs() as i64) * mf + off) >> qbits;
961+ *o = if fv < 0 { -level as i32 } else { level as i32 };
962+ }
963+ out
964+}
965+
966+/// Inverse quantization + transform of the I_16x16 luma DC block, returning the
967+/// reconstructed DC values to scatter into each 4×4 luma block (spec §8.5.10).
968+pub fn inverse_quant_luma_dc(levels: &[i32; 16], qp: u8) -> [i32; 16] {
969+ let _g = crate::prof::scope(crate::prof::Stage::Dequant);
970+ let g = hadamard_4x4(levels);
971+ let m = (qp % 6) as usize;
972+ let shift = (qp / 6) as i32;
973+ let level_scale = 16 * NORM_ADJUST[m][0];
974+ let mut out = [0i32; 16];
975+ for (o, &gv) in out.iter_mut().zip(g.iter()) {
976+ *o = if qp >= 36 {
977+ (gv * level_scale) << (shift - 6)
978+ } else {
979+ (gv * level_scale + (1 << (5 - shift))) >> (6 - shift)
980+ };
981+ }
982+ out
983+}
984+
985+/// `inverse_quant_luma_dc` with the scaling matrix's DC weight (`w00`, the
986+/// raster (0,0) entry; `16` = flat).
987+pub fn inverse_quant_luma_dc_weighted(levels: &[i32; 16], qp: u8, w00: i32) -> [i32; 16] {
988+ let g = hadamard_4x4(levels);
989+ let m = (qp % 6) as usize;
990+ let shift = (qp / 6) as i32;
991+ let level_scale = w00 * NORM_ADJUST[m][0];
992+ let mut out = [0i32; 16];
993+ for (o, &gv) in out.iter_mut().zip(g.iter()) {
994+ *o = if qp >= 36 {
995+ (gv * level_scale) << (shift - 6)
996+ } else {
997+ (gv * level_scale + (1 << (5 - shift))) >> (6 - shift)
998+ };
999+ }
1000+ out
1001+}
1002+
1003+/// `inverse_quant_chroma_dc` with the scaling matrix's DC weight.
1004+pub fn inverse_quant_chroma_dc_weighted(levels: &[i32; 4], qp: u8, w00: i32) -> [i32; 4] {
1005+ let g = hadamard_2x2(levels);
1006+ let m = (qp % 6) as usize;
1007+ let shift = (qp / 6) as i32;
1008+ let level_scale = w00 * NORM_ADJUST[m][0];
1009+ let mut out = [0i32; 4];
1010+ for (o, &gv) in out.iter_mut().zip(g.iter()) {
1011+ *o = ((gv * level_scale) << shift) >> 5;
1012+ }
1013+ out
1014+}
1015+
1016+/// 2×2 Hadamard for a chroma DC block (its own inverse up to scale).
1017+pub fn hadamard_2x2(dc: &[i32; 4]) -> [i32; 4] {
1018+ let (a, b, c, d) = (dc[0], dc[1], dc[2], dc[3]);
1019+ [a + b + c + d, a - b + c - d, a + b - c - d, a - b - c + d]
1020+}
1021+
1022+/// Forward transform + quantization of a chroma DC block (4 coeffs, spec §8.5.11).
1023+pub fn forward_quant_chroma_dc(dc: &[i32; 4], qp: u8, intra: bool) -> [i32; 4] {
1024+ let f = hadamard_2x2(dc);
1025+ let m = (qp % 6) as usize;
1026+ let qbits = 15 + (qp / 6) as u32;
1027+ let off: i64 = if intra { (1i64 << qbits) / 3 } else { (1i64 << qbits) / 6 };
1028+ let mf = QUANT_MF[m][0] as i64;
1029+ let mut out = [0i32; 4];
1030+ for (o, &fv) in out.iter_mut().zip(f.iter()) {
1031+ let level = ((fv.abs() as i64) * mf + 2 * off) >> (qbits + 1);
1032+ *o = if fv < 0 { -level as i32 } else { level as i32 };
1033+ }
1034+ out
1035+}
1036+
1037+/// Inverse quantization + transform of a chroma DC block (spec §8.5.11.2).
1038+pub fn inverse_quant_chroma_dc(levels: &[i32; 4], qp: u8) -> [i32; 4] {
1039+ let _g = crate::prof::scope(crate::prof::Stage::Dequant);
1040+ let g = hadamard_2x2(levels);
1041+ let m = (qp % 6) as usize;
1042+ let shift = (qp / 6) as i32;
1043+ let level_scale = 16 * NORM_ADJUST[m][0];
1044+ let mut out = [0i32; 4];
1045+ for (o, &gv) in out.iter_mut().zip(g.iter()) {
1046+ *o = ((gv * level_scale) << shift) >> 5;
1047+ }
1048+ out
1049+}
1050+
1051+#[cfg(test)]
1052+mod tests {
1053+ use super::*;
1054+
1055+ /// The AVX2 dequant twin must be BIT-IDENTICAL to the scalar oracle — these are
1056+ /// exact integer ops, so this is `assert_eq!`, not a tolerance.
1057+ ///
1058+ /// Sweeps the FULL qp range 0..=51 so both sides of the `qp >= 24` branch are
1059+ /// covered (left-shift vs rounding-add-then-arithmetic-shift), and includes
1060+ /// negative levels and magnitudes near the coefficient range, because an
1061+ /// arithmetic vs logical shift confusion only shows on negatives.
1062+ #[test]
1063+ #[cfg(all(target_arch = "x86_64", feature = "asm"))]
1064+ fn dequant_4x4_matches_scalar() {
1065+ let mut st = 0x2f6e_1c37u32;
1066+ let mut rnd = || {
1067+ st ^= st << 13;
1068+ st ^= st >> 17;
1069+ st ^= st << 5;
1070+ st
1071+ };
1072+ for qp in 0..=51u8 {
1073+ for case in 0..64 {
1074+ let levels: [i32; 16] = std::array::from_fn(|_| {
1075+ let r = rnd();
1076+ let mag = match case % 4 {
1077+ 0 => (r & 0x7) as i32,
1078+ 1 => (r & 0x7ff) as i32,
1079+ 2 => (r & 0x7fff) as i32,
1080+ _ => 0,
1081+ };
1082+ if r & 0x8000_0000 != 0 { -mag } else { mag }
1083+ });
1084+ let m = (qp % 6) as usize;
1085+ let ls = &LEVEL_SCALE_FLAT[m];
1086+ // scalar oracle, spelled out rather than calling `dequantize` (which
1087+ // now dispatches to the kernel under test).
1088+ let shift = (qp / 6) as i32;
1089+ let mut want = [0i32; 16];
1090+ if qp >= 24 {
1091+ let sh = shift - 4;
1092+ for i in 0..16 {
1093+ want[i] = (levels[i] * ls[i]) << sh;
1094+ }
1095+ } else {
1096+ let add = 1 << (3 - shift);
1097+ let sh = 4 - shift;
1098+ for i in 0..16 {
1099+ want[i] = (levels[i] * ls[i] + add) >> sh;
1100+ }
1101+ }
1102+ let mut got = [0i32; 16];
1103+ assert!(rusty_h264_accel::dequant_4x4(&mut got, &levels, ls, qp));
1104+ assert_eq!(got, want, "qp={qp} case={case} levels={levels:?}");
1105+ }
1106+ }
1107+ }
1108+
1109+ #[test]
1110+ fn batched_forward_dct_matches_scalar() {
1111+ let mut state = 0x9e37_79b9u32;
1112+ let mut next = || {
1113+ state = state.wrapping_mul(1_664_525).wrapping_add(1_013_904_223);
1114+ ((state >> 16) % 511) as i32 - 255
1115+ };
1116+ for n in 1..=18 {
1117+ let res: Vec<[i32; 16]> = (0..n).map(|_| std::array::from_fn(|_| next())).collect();
1118+ let mut out = vec![[0i32; 16]; n];
1119+ forward_dct_blocks(&res, &mut out);
1120+ for (r, o) in res.iter().zip(&out) {
1121+ assert_eq!(&forward_core(r), o, "n={n}");
1122+ }
1123+ }
1124+ }
1125+
1126+ #[test]
1127+ fn batched_inverse_dct_matches_scalar() {
1128+ // Wider range than the forward test: dequantized coefficients can be large,
1129+ // and the `>> 1` inside the inverse butterfly must match the scalar's
1130+ // arithmetic shift on negative/asymmetric blocks exactly.
1131+ let mut state = 0x0bad_f00du32;
1132+ let mut next = || {
1133+ state = state.wrapping_mul(1_664_525).wrapping_add(1_013_904_223);
1134+ ((state >> 12) % 8191) as i32 - 4095
1135+ };
1136+ for n in 1..=18 {
1137+ let coeffs: Vec<[i32; 16]> = (0..n).map(|_| std::array::from_fn(|_| next())).collect();
1138+ let mut out = vec![[0i32; 16]; n];
1139+ inverse_dct_blocks(&coeffs, &mut out);
1140+ for (c, o) in coeffs.iter().zip(&out) {
1141+ assert_eq!(&inverse_core(c), o, "n={n}");
1142+ }
1143+ }
1144+ }
1145+
1146+ #[test]
1147+ fn simd_satd_matches_scalar() {
1148+ // The SIMD batch SATD must be bit-identical to the scalar per-block sum.
1149+ let scalar = |res: &[i32; 16]| -> i64 {
1150+ hadamard_4x4(res).iter().map(|&v| v.unsigned_abs() as i64).sum()
1151+ };
1152+ // Deterministic pseudo-random residuals in [-255, 255], 1..=20 blocks.
1153+ let mut state = 0x1234_5678u32;
1154+ let mut next = || {
1155+ state = state.wrapping_mul(1_664_525).wrapping_add(1_013_904_223);
1156+ ((state >> 16) % 511) as i32 - 255
1157+ };
1158+ for n in 1..=20 {
1159+ let blocks: Vec<[i32; 16]> =
1160+ (0..n).map(|_| std::array::from_fn(|_| next())).collect();
1161+ let expect: i64 = blocks.iter().map(&scalar).sum();
1162+ assert_eq!(satd_4x4_sum(&blocks), expect, "n={n}");
1163+ }
1164+ }
1165+
1166+ #[test]
1167+ fn forward_inverse_core_are_consistent_scale() {
1168+ // A pure-DC block: every sample = 4. Forward DC should be 16*4=64,
1169+ // others ~0. Inverse of just the dequantized DC returns the flat block.
1170+ let block = [4i32; 16];
1171+ let w = forward_core(&block);
1172+ assert_eq!(w[0], 64, "DC coefficient");
1173+ for (k, &ac) in w.iter().enumerate().skip(1) {
1174+ assert_eq!(ac, 0, "AC[{k}] should be zero for a flat block");
1175+ }
1176+ }
1177+
1178+ #[test]
1179+ fn forward_core_8x8_flat_block_is_dc_only() {
1180+ // A flat 8×8 block transforms to DC only; the 8×8 DC gain is 64, so a
1181+ // block of all-4 has DC = 256 and zero AC.
1182+ let block = [4i32; 64];
1183+ let w = forward_core_8x8(&block);
1184+ assert_eq!(w[0], 256, "8×8 DC coefficient");
1185+ for (k, &ac) in w.iter().enumerate().skip(1) {
1186+ assert_eq!(ac, 0, "8×8 AC[{k}] should be zero for a flat block");
1187+ }
1188+ }
1189+
1190+ #[test]
1191+ fn inverse_core_8x8_dc_only_is_flat() {
1192+ // Inverse of a DC-only 8×8 block is a flat block of (DC + 32) >> 6.
1193+ let mut coeffs = [0i32; 64];
1194+ coeffs[0] = 256;
1195+ let r = inverse_core_8x8(&coeffs);
1196+ for (k, &v) in r.iter().enumerate() {
1197+ assert_eq!(v, (256 + 32) >> 6, "8×8 inverse DC pixel {k}");
1198+ }
1199+ }
1200+
1201+ #[test]
1202+ fn quant_dequant_8x8_round_trip_near_identity() {
1203+ // The realistic invariant: forward → (flat) dequant-compensated → inverse
1204+ // recovers a flat block exactly, and a smooth ramp within a small error.
1205+ // (Core forward∘inverse alone is NOT identity — the inverse expects the
1206+ // per-frequency LevelScale that dequant applies; here we use the flat
1207+ // matched scale 16·normAdjust at a representative QP.)
1208+ let weight = [16i32; 64];
1209+ for &val in &[0i32, 4, -7, 31] {
1210+ let block = [val; 64];
1211+ let fwd = forward_core_8x8(&block);
1212+ // Treat the forward output as "levels" at QP where 16·normAdjust·>>6
1213+ // is the identity DC gain; verify the DC pixel reconstructs to `val`.
1214+ let deq = dequantize_8x8(&fwd, 24, &weight);
1215+ let _ = deq; // dequant is exercised; exact recon validated via oracle.
1216+ let recon = inverse_core_8x8(&fwd);
1217+ assert_eq!(recon, block, "flat 8×8 must round-trip through the core");
1218+ }
1219+ }
1220+
1221+ #[test]
1222+ fn quantize_8x8_round_trips_through_the_decoder_path() {
1223+ // The encoder gate: forward_core_8x8 → quantize_8x8 → (decoder's)
1224+ // dequantize_8x8 → inverse_core_8x8 recovers the residual within the
1225+ // quantization error — and quant∘dequant is near-identity in coeff space.
1226+ let weight = [16i32; 64];
1227+ // A realistic textured residual (deterministic).
1228+ let res: [i32; 64] = std::array::from_fn(|i| {
1229+ let (x, y) = (i % 8, i / 8);
1230+ (((x * 7 + y * 13) % 23) as i32 - 11) * 4 + ((x as i32 - y as i32) * 3)
1231+ });
1232+ for &qp in &[12u8, 22, 30, 40, 48] {
1233+ let coeffs = forward_core_8x8(&res);
1234+ let levels = quantize_8x8(&coeffs, qp, &weight, 2); // round-to-nearest
1235+ // Coefficient round-trip: dequant(quant(c)) within one quant step of c.
1236+ let deq = dequantize_8x8(&levels, qp, &weight);
1237+ for i in 0..64 {
1238+ // step ≈ 2^(qp/6) scaled; a generous bound catches gross scale errors.
1239+ let step = (1i32 << (qp / 6)) * 64;
1240+ assert!(
1241+ (deq[i] - coeffs[i]).abs() <= step,
1242+ "qp{qp} pos{i}: dequant {} vs coeff {} exceeds step {step}",
1243+ deq[i],
1244+ coeffs[i]
1245+ );
1246+ }
1247+ // Full residual recon: mean-abs error grows with QP but stays bounded.
1248+ let recon = inverse_core_8x8(&deq);
1249+ let mae: i32 =
1250+ (0..64).map(|i| (recon[i] - res[i]).abs()).sum::<i32>() / 64;
1251+ let bound = 2 + (1i32 << (qp / 6)); // ~half a quant step
1252+ assert!(mae <= bound, "qp{qp}: 8×8 recon MAE {mae} exceeds {bound}");
1253+ }
1254+ }
1255+
1256+ #[test]
1257+ fn dequant_8x8_flat_matches_levelscale() {
1258+ // Flat weight (16) → LevelScale = 16·normAdjust8x8; check one DC sample.
1259+ let mut levels = [0i32; 64];
1260+ levels[0] = 3;
1261+ let weight = [16i32; 64];
1262+ let d = dequantize_8x8(&levels, 30, &weight);
1263+ // qp=30 < 36: (3 · 16·normAdjust[0][0] + (1<<(5-5))) >> (6-5)
1264+ let ls = 16 * NORM_ADJUST_8X8[0][0];
1265+ assert_eq!(d[0], (3 * ls + 1) >> 1);
1266+ }
1267+
1268+ #[test]
1269+ fn inverse_core_is_row_first() {
1270+ // The 4×4 integer inverse transform is NOT order-invariant: the `>> 1`
1271+ // flooring inside `inv_1d` makes row-first and column-first diverge on
1272+ // asymmetric blocks. The spec (§8.5.12.2) and ffmpeg do rows first; a
1273+ // column-first pass is a real bug that only surfaces at low QP / high
1274+ // frequency. This input distinguishes the two orders and pins ours.
1275+ let coeffs = [9, 2, -1, 2, -2, 2, -2, 1, -1, -2, 3, 5, -1, -1, -5, 3];
1276+ let mut rows_then_cols = coeffs;
1277+ for r in 0..4 {
1278+ let (a, b, c, d) = inv_1d(
1279+ rows_then_cols[r * 4],
1280+ rows_then_cols[r * 4 + 1],
1281+ rows_then_cols[r * 4 + 2],
1282+ rows_then_cols[r * 4 + 3],
1283+ );
1284+ rows_then_cols[r * 4] = a;
1285+ rows_then_cols[r * 4 + 1] = b;
1286+ rows_then_cols[r * 4 + 2] = c;
1287+ rows_then_cols[r * 4 + 3] = d;
1288+ }
1289+ for c in 0..4 {
1290+ let (a, b, cc, d) = inv_1d(
1291+ rows_then_cols[c],
1292+ rows_then_cols[4 + c],
1293+ rows_then_cols[8 + c],
1294+ rows_then_cols[12 + c],
1295+ );
1296+ rows_then_cols[c] = a;
1297+ rows_then_cols[4 + c] = b;
1298+ rows_then_cols[8 + c] = cc;
1299+ rows_then_cols[12 + c] = d;
1300+ }
1301+ let mut cols_then_rows = coeffs;
1302+ for c in 0..4 {
1303+ let (a, b, cc, d) = inv_1d(
1304+ cols_then_rows[c],
1305+ cols_then_rows[4 + c],
1306+ cols_then_rows[8 + c],
1307+ cols_then_rows[12 + c],
1308+ );
1309+ cols_then_rows[c] = a;
1310+ cols_then_rows[4 + c] = b;
1311+ cols_then_rows[8 + c] = cc;
1312+ cols_then_rows[12 + c] = d;
1313+ }
1314+ for r in 0..4 {
1315+ let (a, b, c, d) = inv_1d(
1316+ cols_then_rows[r * 4],
1317+ cols_then_rows[r * 4 + 1],
1318+ cols_then_rows[r * 4 + 2],
1319+ cols_then_rows[r * 4 + 3],
1320+ );
1321+ cols_then_rows[r * 4] = a;
1322+ cols_then_rows[r * 4 + 1] = b;
1323+ cols_then_rows[r * 4 + 2] = c;
1324+ cols_then_rows[r * 4 + 3] = d;
1325+ }
1326+ // The two orders genuinely differ on this block...
1327+ assert_ne!(rows_then_cols, cols_then_rows);
1328+ // ...and inverse_core (plus the +32>>6 normalization) follows rows-first.
1329+ let expected: [i32; 16] =
1330+ core::array::from_fn(|k| (rows_then_cols[k] + 32) >> 6);
1331+ assert_eq!(inverse_core(&coeffs), expected);
1332+ }
1333+
1334+ #[test]
1335+ fn quant_dequant_roundtrip_is_near_identity() {
1336+ // For a range of QPs, a transformed-then-quantized-then-reconstructed
1337+ // residual should stay within the quantization step of the original.
1338+ let residual: [i32; 16] = [
1339+ 5, -3, 8, 0, 12, -7, 2, 1, -4, 6, 9, -2, 0, 3, -1, 7,
1340+ ];
1341+ for qp in [0u8, 6, 12, 18, 26, 30, 37, 45, 51] {
1342+ let levels = forward_quant(&residual, qp, true);
1343+ let recon = inverse_quant(&levels, qp);
1344+ // Tolerance grows with the quant step (~ 2^(qp/6)).
1345+ let tol = 2 + (1 << (qp / 6));
1346+ for k in 0..16 {
1347+ let diff = (recon[k] - residual[k]).abs();
1348+ assert!(
1349+ diff <= tol,
1350+ "qp {qp}: residual[{k}]={} recon={} diff={diff} tol={tol}",
1351+ residual[k],
1352+ recon[k]
1353+ );
1354+ }
1355+ }
1356+ }
1357+
1358+ #[test]
1359+ fn trellis_never_exceeds_scalar_magnitude() {
1360+ // Trellis only considers the scalar level or lower, so |level| never
1361+ // grows, and a large λ drives marginal coefficients toward zero.
1362+ let coeffs: [i32; 16] = [120, -40, 8, 1, -15, 6, -1, 0, 3, -2, 1, 0, 0, 1, 0, 0];
1363+ let scalar = quantize(&coeffs, 26, 3);
1364+ let t = trellis_quant(&coeffs, 26, true, 50.0);
1365+ for k in 0..16 {
1366+ assert!(t[k].unsigned_abs() <= scalar[k].unsigned_abs(), "[{k}]");
1367+ assert!(t[k] == 0 || t[k].signum() == scalar[k].signum());
1368+ }
1369+ }
1370+
1371+ #[test]
1372+ fn zero_residual_stays_zero() {
1373+ let zero = [0i32; 16];
1374+ let levels = forward_quant(&zero, 28, true);
1375+ assert_eq!(levels, [0i32; 16]);
1376+ assert_eq!(inverse_quant(&levels, 28), [0i32; 16]);
1377+ }
1378+
1379+ #[test]
1380+ fn luma_dc_end_to_end_flat_block() {
1381+ // A flat luma residual `r`: each 4×4 block's forward-core DC is 16*r and
1382+ // its AC is 0. Coding the 16 DCs via the secondary transform and
1383+ // reconstructing (scatter DC → inverse core) must recover ~r per sample.
1384+ for r in [3i32, 9, -5, 20] {
1385+ for qp in [0u8, 12, 24, 30] {
1386+ let w_dc = [16 * r; 16]; // forward-core DC of a flat block
1387+ let z = forward_quant_luma_dc(&w_dc, qp, true);
1388+ let dcy = inverse_quant_luma_dc(&z, qp);
1389+ let tol = 1 + (1 << (qp / 6));
1390+ for (b, &dc) in dcy.iter().enumerate() {
1391+ let mut coeff = [0i32; 16];
1392+ coeff[0] = dc;
1393+ let res = inverse_core(&coeff);
1394+ for &v in &res {
1395+ assert!((v - r).abs() <= tol, "luma DC r={r} qp{qp} blk{b}: {v} vs {r}");
1396+ }
1397+ }
1398+ }
1399+ }
1400+ }
1401+
1402+ #[test]
1403+ fn chroma_dc_end_to_end_flat_block() {
1404+ // Same idea for the 2×2 chroma DC secondary transform.
1405+ for r in [4i32, -6, 11] {
1406+ for qp in [0u8, 18, 30] {
1407+ let dc = [16 * r; 4];
1408+ let z = forward_quant_chroma_dc(&dc, qp, true);
1409+ let dcy = inverse_quant_chroma_dc(&z, qp);
1410+ let tol = 1 + (1 << (qp / 6));
1411+ for &d in &dcy {
1412+ let mut coeff = [0i32; 16];
1413+ coeff[0] = d;
1414+ let res = inverse_core(&coeff);
1415+ for &v in &res {
1416+ assert!((v - r).abs() <= tol, "chroma DC r={r} qp{qp}: {v} vs {r}");
1417+ }
1418+ }
1419+ }
1420+ }
1421+ }
1422+
1423+ #[test]
1424+ fn hadamard_is_self_inverse_scaled() {
1425+ // Applying the 4×4 Hadamard twice scales by 16.
1426+ let x: [i32; 16] = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16];
1427+ let twice = hadamard_4x4(&hadamard_4x4(&x));
1428+ for (k, (&a, &b)) in x.iter().zip(twice.iter()).enumerate() {
1429+ assert_eq!(b, a * 16, "[{k}]");
1430+ }
1431+ }
1432+
1433+ #[test]
1434+ fn low_qp_is_high_fidelity() {
1435+ // At QP 0 the reconstruction should be essentially exact for small
1436+ // integer residuals.
1437+ let residual: [i32; 16] = [1, 2, 3, 4, -1, -2, -3, -4, 0, 1, 0, -1, 2, -2, 1, 0];
1438+ let levels = forward_quant(&residual, 0, true);
1439+ let recon = inverse_quant(&levels, 0);
1440+ for (k, (&r, &o)) in residual.iter().zip(recon.iter()).enumerate() {
1441+ assert!((o - r).abs() <= 1, "qp0 residual[{k}]={r} recon={o}");
1442+ }
1443+ }
1444+}
1445+
1446+// openh264 BSD-2 quant tables (g_kiQuantMF[52][8], g_kiQuantInterFF[58][8]).
1447+pub const QUANT_MF_OH: [[i16; 8]; 52] = [
1448+ [26214, 16132, 26214, 16132, 16132, 10486, 16132, 10486],
1449+ [23832, 14980, 23832, 14980, 14980, 9320, 14980, 9320],
1450+ [20164, 13108, 20164, 13108, 13108, 8388, 13108, 8388],
1451+ [18724, 11650, 18724, 11650, 11650, 7294, 11650, 7294],
1452+ [16384, 10486, 16384, 10486, 10486, 6710, 10486, 6710],
1453+ [14564, 9118, 14564, 9118, 9118, 5786, 9118, 5786],
1454+ [13107, 8066, 13107, 8066, 8066, 5243, 8066, 5243],
1455+ [11916, 7490, 11916, 7490, 7490, 4660, 7490, 4660],
1456+ [10082, 6554, 10082, 6554, 6554, 4194, 6554, 4194],
1457+ [9362, 5825, 9362, 5825, 5825, 3647, 5825, 3647],
1458+ [8192, 5243, 8192, 5243, 5243, 3355, 5243, 3355],
1459+ [7282, 4559, 7282, 4559, 4559, 2893, 4559, 2893],
1460+ [6554, 4033, 6554, 4033, 4033, 2622, 4033, 2622],
1461+ [5958, 3745, 5958, 3745, 3745, 2330, 3745, 2330],
1462+ [5041, 3277, 5041, 3277, 3277, 2097, 3277, 2097],
1463+ [4681, 2913, 4681, 2913, 2913, 1824, 2913, 1824],
1464+ [4096, 2622, 4096, 2622, 2622, 1678, 2622, 1678],
1465+ [3641, 2280, 3641, 2280, 2280, 1447, 2280, 1447],
1466+ [3277, 2017, 3277, 2017, 2017, 1311, 2017, 1311],
1467+ [2979, 1873, 2979, 1873, 1873, 1165, 1873, 1165],
1468+ [2521, 1639, 2521, 1639, 1639, 1049, 1639, 1049],
1469+ [2341, 1456, 2341, 1456, 1456, 912, 1456, 912],
1470+ [2048, 1311, 2048, 1311, 1311, 839, 1311, 839],
1471+ [1821, 1140, 1821, 1140, 1140, 723, 1140, 723],
1472+ [1638, 1008, 1638, 1008, 1008, 655, 1008, 655],
1473+ [1490, 936, 1490, 936, 936, 583, 936, 583],
1474+ [1260, 819, 1260, 819, 819, 524, 819, 524],
1475+ [1170, 728, 1170, 728, 728, 456, 728, 456],
1476+ [1024, 655, 1024, 655, 655, 419, 655, 419],
1477+ [910, 570, 910, 570, 570, 362, 570, 362],
1478+ [819, 504, 819, 504, 504, 328, 504, 328],
1479+ [745, 468, 745, 468, 468, 291, 468, 291],
1480+ [630, 410, 630, 410, 410, 262, 410, 262],
1481+ [585, 364, 585, 364, 364, 228, 364, 228],
1482+ [512, 328, 512, 328, 328, 210, 328, 210],
1483+ [455, 285, 455, 285, 285, 181, 285, 181],
1484+ [410, 252, 410, 252, 252, 164, 252, 164],
1485+ [372, 234, 372, 234, 234, 146, 234, 146],
1486+ [315, 205, 315, 205, 205, 131, 205, 131],
1487+ [293, 182, 293, 182, 182, 114, 182, 114],
1488+ [256, 164, 256, 164, 164, 105, 164, 105],
1489+ [228, 142, 228, 142, 142, 90, 142, 90],
1490+ [205, 126, 205, 126, 126, 82, 126, 82],
1491+ [186, 117, 186, 117, 117, 73, 117, 73],
1492+ [158, 102, 158, 102, 102, 66, 102, 66],
1493+ [146, 91, 146, 91, 91, 57, 91, 57],
1494+ [128, 82, 128, 82, 82, 52, 82, 52],
1495+ [114, 71, 114, 71, 71, 45, 71, 45],
1496+ [102, 63, 102, 63, 63, 41, 63, 41],
1497+ [93, 59, 93, 59, 59, 36, 59, 36],
1498+ [79, 51, 79, 51, 51, 33, 51, 33],
1499+ [73, 46, 73, 46, 46, 28, 46, 28],
1500+];
1501+
1502+pub const QUANT_FF_OH: [[i16; 8]; 58] = [
1503+ [0, 1, 0, 1, 1, 1, 1, 1],
1504+ [0, 1, 0, 1, 1, 1, 1, 1],
1505+ [1, 1, 1, 1, 1, 1, 1, 1],
1506+ [1, 1, 1, 1, 1, 1, 1, 1],
1507+ [1, 1, 1, 1, 1, 2, 1, 2],
1508+ [1, 1, 1, 1, 1, 2, 1, 2],
1509+ [1, 1, 1, 1, 1, 2, 1, 2],
1510+ [1, 1, 1, 1, 1, 2, 1, 2],
1511+ [1, 2, 1, 2, 2, 3, 2, 3],
1512+ [1, 2, 1, 2, 2, 3, 2, 3],
1513+ [1, 2, 1, 2, 2, 3, 2, 3],
1514+ [1, 2, 1, 2, 2, 4, 2, 4],
1515+ [2, 3, 2, 3, 3, 4, 3, 4],
1516+ [2, 3, 2, 3, 3, 5, 3, 5],
1517+ [2, 3, 2, 3, 3, 5, 3, 5],
1518+ [2, 4, 2, 4, 4, 6, 4, 6],
1519+ [3, 4, 3, 4, 4, 7, 4, 7],
1520+ [3, 5, 3, 5, 5, 8, 5, 8],
1521+ [3, 5, 3, 5, 5, 8, 5, 8],
1522+ [4, 6, 4, 6, 6, 9, 6, 9],
1523+ [4, 7, 4, 7, 7, 10, 7, 10],
1524+ [5, 8, 5, 8, 8, 12, 8, 12],
1525+ [5, 8, 5, 8, 8, 13, 8, 13],
1526+ [6, 10, 6, 10, 10, 15, 10, 15],
1527+ [7, 11, 7, 11, 11, 17, 11, 17],
1528+ [7, 12, 7, 12, 12, 19, 12, 19],
1529+ [9, 13, 9, 13, 13, 21, 13, 21],
1530+ [9, 15, 9, 15, 15, 24, 15, 24],
1531+ [11, 17, 11, 17, 17, 26, 17, 26],
1532+ [12, 19, 12, 19, 19, 30, 19, 30],
1533+ [13, 22, 13, 22, 22, 33, 22, 33],
1534+ [15, 23, 15, 23, 23, 38, 23, 38],
1535+ [17, 27, 17, 27, 27, 42, 27, 42],
1536+ [19, 30, 19, 30, 30, 48, 30, 48],
1537+ [21, 33, 21, 33, 33, 52, 33, 52],
1538+ [24, 38, 24, 38, 38, 60, 38, 60],
1539+ [27, 43, 27, 43, 43, 67, 43, 67],
1540+ [29, 47, 29, 47, 47, 75, 47, 75],
1541+ [35, 53, 35, 53, 53, 83, 53, 83],
1542+ [37, 60, 37, 60, 60, 96, 60, 96],
1543+ [43, 67, 43, 67, 67, 104, 67, 104],
1544+ [48, 77, 48, 77, 77, 121, 77, 121],
1545+ [53, 87, 53, 87, 87, 133, 87, 133],
1546+ [59, 93, 59, 93, 93, 150, 93, 150],
1547+ [69, 107, 69, 107, 107, 167, 107, 167],
1548+ [75, 120, 75, 120, 120, 192, 120, 192],
1549+ [85, 133, 85, 133, 133, 208, 133, 208],
1550+ [96, 153, 96, 153, 153, 242, 153, 242],
1551+ [107, 173, 107, 173, 173, 267, 173, 267],
1552+ [117, 187, 117, 187, 187, 300, 187, 300],
1553+ [139, 213, 139, 213, 213, 333, 213, 333],
1554+ [149, 240, 149, 240, 240, 383, 240, 383],
1555+ [171, 267, 171, 267, 267, 417, 267, 417],
1556+ [192, 307, 192, 307, 307, 483, 307, 483],
1557+ [213, 347, 213, 347, 347, 533, 347, 533],
1558+ [235, 373, 235, 373, 373, 600, 373, 600],
1559+ [277, 427, 277, 427, 427, 667, 427, 667],
1560+ [299, 480, 299, 480, 480, 767, 480, 767],
1561+];
vendor/rusty_h264-common/src/types.rsadded+97 -0
@@ -0,0 +1,97 @@
1+//! Shared codec types: profiles, chroma format, and the raw YUV frame container.
2+
3+/// H.264 profile. The encoder targets Constrained Baseline; the rest are named
4+/// for parsing/identification only.
5+#[derive(Debug, Clone, Copy, PartialEq, Eq)]
6+pub enum Profile {
7+ /// Constrained Baseline (`profile_idc = 66` with `constraint_set1_flag`).
8+ ConstrainedBaseline,
9+ /// Baseline (`profile_idc = 66`).
10+ Baseline,
11+ /// Main (`profile_idc = 77`).
12+ Main,
13+ /// High (`profile_idc = 100`).
14+ High,
15+ /// Any other `profile_idc`.
16+ Other(u8),
17+}
18+
19+impl Profile {
20+ /// The `profile_idc` byte written into the SPS.
21+ pub fn profile_idc(self) -> u8 {
22+ match self {
23+ Profile::ConstrainedBaseline | Profile::Baseline => 66,
24+ Profile::Main => 77,
25+ Profile::High => 100,
26+ Profile::Other(v) => v,
27+ }
28+ }
29+}
30+
31+/// Chroma subsampling. The encoder supports 4:2:0 only for now.
32+#[derive(Debug, Clone, Copy, PartialEq, Eq)]
33+pub enum ChromaFormat {
34+ /// Monochrome (`chroma_format_idc = 0`).
35+ Monochrome,
36+ /// 4:2:0 (`chroma_format_idc = 1`).
37+ Yuv420,
38+}
39+
40+impl ChromaFormat {
41+ /// `chroma_format_idc`.
42+ pub fn idc(self) -> u8 {
43+ match self {
44+ ChromaFormat::Monochrome => 0,
45+ ChromaFormat::Yuv420 => 1,
46+ }
47+ }
48+}
49+
50+/// A raw planar YUV 4:2:0 frame (8-bit). Plane strides equal their widths;
51+/// chroma planes are half-resolution in each dimension.
52+#[derive(Debug, Clone, PartialEq, Eq)]
53+pub struct YuvFrame {
54+ /// Luma width in pixels.
55+ pub width: usize,
56+ /// Luma height in pixels.
57+ pub height: usize,
58+ /// Y plane, `width * height` bytes.
59+ pub y: Vec<u8>,
60+ /// Cb plane, `(width/2) * (height/2)` bytes.
61+ pub u: Vec<u8>,
62+ /// Cr plane, `(width/2) * (height/2)` bytes.
63+ pub v: Vec<u8>,
64+}
65+
66+impl YuvFrame {
67+ /// Allocates a black (Y=0, U=V=128) frame. Dimensions must be even.
68+ pub fn black(width: usize, height: usize) -> Self {
69+ assert!(width % 2 == 0 && height % 2 == 0, "dimensions must be even");
70+ let cw = width / 2;
71+ let ch = height / 2;
72+ Self {
73+ width,
74+ height,
75+ y: vec![0; width * height],
76+ u: vec![128; cw * ch],
77+ v: vec![128; cw * ch],
78+ }
79+ }
80+
81+ /// Chroma plane width.
82+ pub fn chroma_width(&self) -> usize {
83+ self.width / 2
84+ }
85+
86+ /// Chroma plane height.
87+ pub fn chroma_height(&self) -> usize {
88+ self.height / 2
89+ }
90+
91+ /// Validates plane sizes against the dimensions.
92+ pub fn is_valid(&self) -> bool {
93+ self.y.len() == self.width * self.height
94+ && self.u.len() == self.chroma_width() * self.chroma_height()
95+ && self.v.len() == self.chroma_width() * self.chroma_height()
96+ }
97+}