From c8f62cbb65b8a92a4ae84482b7017d4e252642d1 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Ahmet=20Kaan=20G=C3=BCm=C3=BC=C5=9F?= Date: Thu, 13 Aug 2026 01:10:35 +0300 Subject: [PATCH] =?UTF-8?q?=F0=9F=90=9B=20fix(engine):=20the=20codec=20sto?= =?UTF-8?q?ps=20replacing=20the=20whole=20program's=20allocator?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit `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. --- Cargo.lock | 31 - Cargo.toml | 19 +- crates/engine/Cargo.toml | 12 +- vendor/rusty_h264-common/Cargo.toml | 74 + vendor/rusty_h264-common/README.md | 122 + vendor/rusty_h264-common/build.rs | 18 + .../examples/bs_layout_ceiling.rs | 251 ++ .../examples/deblock_anatomy.rs | 177 + vendor/rusty_h264-common/src/aligned.rs | 55 + vendor/rusty_h264-common/src/bit_reader.rs | 343 ++ vendor/rusty_h264-common/src/bit_writer.rs | 319 ++ vendor/rusty_h264-common/src/cabac_tables.rs | 644 ++++ vendor/rusty_h264-common/src/cavlc.rs | 821 +++++ vendor/rusty_h264-common/src/deblock.rs | 2881 +++++++++++++++++ vendor/rusty_h264-common/src/inter.rs | 1899 +++++++++++ vendor/rusty_h264-common/src/lib.rs | 57 + vendor/rusty_h264-common/src/nal.rs | 232 ++ vendor/rusty_h264-common/src/predict.rs | 907 ++++++ vendor/rusty_h264-common/src/prof.rs | 585 ++++ vendor/rusty_h264-common/src/transform.rs | 1561 +++++++++ vendor/rusty_h264-common/src/types.rs | 97 + 21 files changed, 11066 insertions(+), 39 deletions(-) create mode 100644 vendor/rusty_h264-common/Cargo.toml create mode 100644 vendor/rusty_h264-common/README.md create mode 100644 vendor/rusty_h264-common/build.rs create mode 100644 vendor/rusty_h264-common/examples/bs_layout_ceiling.rs create mode 100644 vendor/rusty_h264-common/examples/deblock_anatomy.rs create mode 100644 vendor/rusty_h264-common/src/aligned.rs create mode 100644 vendor/rusty_h264-common/src/bit_reader.rs create mode 100644 vendor/rusty_h264-common/src/bit_writer.rs create mode 100644 vendor/rusty_h264-common/src/cabac_tables.rs create mode 100644 vendor/rusty_h264-common/src/cavlc.rs create mode 100644 vendor/rusty_h264-common/src/deblock.rs create mode 100644 vendor/rusty_h264-common/src/inter.rs create mode 100644 vendor/rusty_h264-common/src/lib.rs create mode 100644 vendor/rusty_h264-common/src/nal.rs create mode 100644 vendor/rusty_h264-common/src/predict.rs create mode 100644 vendor/rusty_h264-common/src/prof.rs create mode 100644 vendor/rusty_h264-common/src/transform.rs create mode 100644 vendor/rusty_h264-common/src/types.rs diff --git a/Cargo.lock b/Cargo.lock index 5054fa5..7185421 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -5019,25 +5019,6 @@ checksum = "cf54715a573b99ac80df0bc206da022bcd442c974952c7b9720069370852e21f" name = "rusty_aac" version = "0.5.0" -[[package]] -name = "rusty_alloc" -version = "0.3.2" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "b5f05c71564028538eeba6e2e08c6a512267e85e6a1584beca45c6f26af8651b" -dependencies = [ - "libc", - "windows-sys 0.60.2", -] - -[[package]] -name = "rusty_alloc-api" -version = "0.3.2" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "65c8c3ecd14424ba980d005147945a745836dea7798d447c419e08be1f79e88f" -dependencies = [ - "rusty_alloc", -] - [[package]] name = "rusty_h264" version = "0.9.1" @@ -5052,11 +5033,8 @@ dependencies = [ [[package]] name = "rusty_h264-common" version = "0.9.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "ed3c3c7ad3a43386460736b7552ab82239bdd703bedcf8c7f5d0032c50cfb8cb" dependencies = [ "bytemuck", - "rusty_alloc-api", "wide", ] @@ -7217,15 +7195,6 @@ dependencies = [ "windows-targets 0.52.6", ] -[[package]] -name = "windows-sys" -version = "0.60.2" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "f2f500e4d28234f72040990ec9d39e3a6b950f9f22d3dba18416c35882612bcb" -dependencies = [ - "windows-targets 0.53.5", -] - [[package]] name = "windows-sys" version = "0.61.2" diff --git a/Cargo.toml b/Cargo.toml index 93e276b..5f1f1d0 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -7,15 +7,16 @@ exclude = [ "vendor/cros-codecs", "vendor/rusty_aac", "vendor/oxideav-h265", + "vendor/rusty_h264-common", ] [workspace.package] version = "0.1.0" edition = "2024" -# Four upstream crates vendored verbatim except for one clearly marked fix each, +# Five upstream crates vendored verbatim except for one clearly marked fix each, # all blockers on this machine and all still unfixed upstream as of -# 0.0.6/0.0.13/0.5.0/0.0.9: +# 0.0.6/0.0.13/0.5.0/0.0.9/0.9.1: # cros-libva - fails to build against libva >= 1.23 headers # cros-codecs - probes VA-API with a 16x16 context that Mesa radeonsi refuses; # and creates every decode context as 8-bit 4:2:0, which no HEVC @@ -38,8 +39,20 @@ edition = "2024" # 69bde5a6e, and it is a plain path dependency (no # `[patch.crates-io]` line) because nothing else in the tree # asks for it. -# Drop `vendor/` entirely once released versions handle all four. +# rusty_h264-common - declares `rusty_alloc` (its authors' own mimalloc +# remake) as the `#[global_allocator]` of whatever application +# links it, under a feature that `rusty_h264-{decoder,encoder}` +# turn on from *their* defaults, so no downstream feature choice +# can decline it. It crashed us: under sustained ruler scrubbing +# edith churns decode-worker threads, and that allocator +# segfaulted inside `span_from_segments` on a new thread's first +# allocation (two cores, 2026-08-13). The patch is the feature +# default and the six-line declaration in `src/lib.rs`; every +# line of codec code is byte-identical to 0.9.1, so decode stays +# bit-exact and the process gets glibc's malloc back. +# Drop `vendor/` entirely once released versions handle all five. [patch.crates-io] cros-libva = { path = "vendor/cros-libva" } cros-codecs = { path = "vendor/cros-codecs" } rusty_aac = { path = "vendor/rusty_aac" } +rusty_h264-common = { path = "vendor/rusty_h264-common" } diff --git a/crates/engine/Cargo.toml b/crates/engine/Cargo.toml index d9da87f..4419a58 100644 --- a/crates/engine/Cargo.toml +++ b/crates/engine/Cargo.toml @@ -44,11 +44,13 @@ miniz_oxide = "0.8" # What that line does not turn off, and cannot: the facade asks for its three # sub-crates with *their* defaults, and `rusty_h264-common`'s default installs # `rusty_alloc` -- a pure-Rust mimalloc remake, MIT -- as the process-wide -# `#[global_allocator]`, for the whole application rather than the codec. No -# feature choice downstream switches it back off; only a vendored `common` -# would. It is not a regression to pay for: the same 2M-allocation churn runs in -# 0.104 s under it against 0.142 s under glibc's, so it stays, and this -# paragraph is the disclosure. Frame-threaded decode arrived in 0.9 as well and +# `#[global_allocator]`, for the whole application rather than the codec. It was +# faster on a synthetic 2M-allocation churn (0.104 s against glibc's 0.142 s) +# and it crashed the editor: sustained scrubbing churns decode-worker threads, +# and it segfaulted on a new thread's *first* allocation. `common` is therefore +# vendored with that declaration removed (workspace root `[patch.crates-io]`), +# which is the only way to decline it -- the codec itself is untouched and still +# bit-exact. Frame-threaded decode arrived in 0.9 as well and # is opt-in through `RS_H264_FRAME_THREADS`, unset here -- the decode loop is # serial exactly as it was. rusty_h264 = { version = "=0.9.1", default-features = false } diff --git a/vendor/rusty_h264-common/Cargo.toml b/vendor/rusty_h264-common/Cargo.toml new file mode 100644 index 0000000..18960db --- /dev/null +++ b/vendor/rusty_h264-common/Cargo.toml @@ -0,0 +1,74 @@ +# THIS FILE IS AUTOMATICALLY GENERATED BY CARGO +# +# When uploading crates to the registry Cargo will automatically +# "normalize" Cargo.toml files for maximal compatibility +# with all versions of Cargo and also rewrite `path` dependencies +# to registry (e.g., crates.io) dependencies. +# +# If you are reading this file be aware that the original Cargo.toml +# will likely look very different (and much more reasonable). +# See Cargo.toml.orig for the original contents. + +[package] +edition = "2021" +rust-version = "1.80" +name = "rusty_h264-common" +version = "0.9.1" +authors = ["Mata Network"] +build = "build.rs" +autolib = false +autobins = false +autoexamples = false +autotests = false +autobenches = false +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." +homepage = "https://www.mata.network/" +documentation = "https://docs.rs/rusty_h264-common" +readme = "README.md" +keywords = [ + "h264", + "avc", + "video", + "codec", + "bitstream", +] +categories = [ + "multimedia::video", + "multimedia::encoding", + "encoding", +] +license = "BSD-2-Clause" +repository = "https://github.com/remade-with-rust/rusty_h264" + +[features] +asm = ["dep:rusty_h264-accel"] +# --- edith patch: `global-alloc` is off by default and inert when asked for --- +# It stays *declared* because `rusty_h264-{decoder,encoder}`'s own defaults name +# `rusty_h264-common/global-alloc`, so removing it would break their manifests; +# it just no longer pulls `rusty_alloc-api` in, and lib.rs no longer installs the +# `#[global_allocator]`. See the note in the workspace root Cargo.toml. +default = [] +global-alloc = [] +profile = [] + +[lib] +name = "rusty_h264_common" +path = "src/lib.rs" + +[[example]] +name = "bs_layout_ceiling" +path = "examples/bs_layout_ceiling.rs" + +[[example]] +name = "deblock_anatomy" +path = "examples/deblock_anatomy.rs" + +[dependencies.bytemuck] +version = "1" + +[dependencies.rusty_h264-accel] +version = "0.9.1" +optional = true + +[dependencies.wide] +version = "0.7" diff --git a/vendor/rusty_h264-common/README.md b/vendor/rusty_h264-common/README.md new file mode 100644 index 0000000..3441e28 --- /dev/null +++ b/vendor/rusty_h264-common/README.md @@ -0,0 +1,122 @@ +# rusty_h264-common + +[![crates.io](https://img.shields.io/crates/v/rusty_h264-common?logo=rust)](https://crates.io/crates/rusty_h264-common) +[![docs.rs](https://img.shields.io/docsrs/rusty_h264-common?logo=docsdotrs)](https://docs.rs/rusty_h264-common) +[![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) +[![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) +[![Remade With Rust](https://img.shields.io/badge/Remade%20With-Rust-000?logo=rust&logoColor=fff)](https://github.com/Remade-With-Rust) +[![By Mata Network](https://img.shields.io/badge/by-Mata%20Network-5b2be0)](https://www.mata.network/) + +> **The foundation both halves of the codec sit on.** Bitstream I/O, Exp-Golomb, +> NAL/Annex-B framing, the integer transforms, intra prediction, motion +> compensation and the deblocking filter — the shared `codec/common` layer of +> the pure-Rust [`rusty_h264`](https://crates.io/crates/rusty_h264) codec. + +**Most users want the facade — [`rusty_h264`](https://crates.io/crates/rusty_h264).** +Depend on this crate directly only if you are building on the primitives (a +custom parser, an analyzer, your own codec) rather than encoding or decoding. + +Part of **[Remade With Rust](https://github.com/Remade-With-Rust)** by +**[Mata Network](https://www.mata.network/)**. + +--- + +## Why it's `forbid(unsafe_code)` + +The bit-twiddling core of an H.264 codec — Exp-Golomb reads off a hostile +bitstream, RBSP emulation handling, block-level pixel loops — is *exactly* where +memory-safety bugs hide in the C implementations. So this crate is +`#![forbid(unsafe_code)]`, and the shared reconstruction path here is what makes +the encoder and decoder agree bit-for-bit. + +The single exception is opt-in and never shipped: the `profile` feature relaxes +the attribute to unlock the `rdtsc` timer in [`prof`](https://docs.rs/rusty_h264-common/latest/rusty_h264_common/prof/) +for stage measurement. The release build forbids `unsafe`. + +## Modules + +| Module | What's in it | +|---|---| +| `bit_writer` / `bit_reader` | MSB-first bit packing and parsing, Exp-Golomb (`ue`/`se`), bounded reads that return `OutOfData` instead of panicking | +| `nal` | NAL units, Annex-B framing (`split_annex_b`), RBSP emulation prevention/unprevention | +| `types` | `YuvFrame` (raw planar I420), `Profile`, `ChromaFormat` | +| `transform` | 4×4 and 8×8 integer transforms, quantization/dequantization, luma & chroma DC Hadamard, scaling matrices | +| `predict` | Intra prediction — `I_16x16`, `I_4x4`, `I_8x8`, chroma 8×8 | +| `inter` | Quarter-pel luma motion compensation (6-tap), chroma MC, the interpolation half-pel planes | +| `deblock` | The in-loop deblocking filter, luma + chroma, 8×8-transform-aware | +| `cavlc` | CAVLC residual coding tables — table-driven **O(1)** decode (was O(bits·candidates)) | +| `cabac_tables` | The 460-context CABAC initialization tables shared by both entropy engines | +| `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 | +| `prof` | Dev-only `rdtsc` stage profiler, behind the `profile` feature — zero cost when off | + +Also exported: `ACCEL: bool`, whether the vendored SIMD kernels are actually +compiled in. Benchmarks read it so a harness that silently fell back to the +scalar twin can't report the fast path's number. + +## Features + +| Feature | Default | Effect | +|---|:--:|---| +| `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`. | +| `profile` | — | Enable the in-process stage profiler. Measurement builds only — never ship it. | + +SIMD is enabled through the facade's default `asm` feature; when this crate is +used standalone the scalar path is the default. + +## Install + +```sh +cargo add rusty_h264-common +``` + +```rust +use rusty_h264_common::BitReader; +use rusty_h264_common::nal::{emulation_unprevent, split_annex_b}; + +// Walk an Annex-B stream and read each NAL's header + first Exp-Golomb field. +for nal in split_annex_b(&stream) { + let rbsp = emulation_unprevent(nal); + let mut r = BitReader::new(&rbsp); + let _forbidden_zero = r.read_bits(1)?; + let _nal_ref_idc = r.read_bits(2)?; + let nal_unit_type = r.read_bits(5)?; + println!("nal type {nal_unit_type}, first ue = {}", r.read_ue()?); +} +``` + +## Where this sits + +| Crate | Role | +|---|---| +| [`rusty_h264`](https://crates.io/crates/rusty_h264) | the public, safe facade API — **depend on this** | +| **[`rusty_h264-common`](https://crates.io/crates/rusty_h264-common)** | **← you are here** — bitstream I/O, transforms, prediction, MC, deblock | +| [`rusty_h264-encoder`](https://crates.io/crates/rusty_h264-encoder) | the encode pipeline | +| [`rusty_h264-decoder`](https://crates.io/crates/rusty_h264-decoder) | the decode pipeline | +| [`rusty_h264-accel`](https://crates.io/crates/rusty_h264-accel) | optional openh264 SIMD asm — the one `unsafe` crate | + +The workspace mirrors Cisco openh264's `codec/` tree; this crate is +`codec/common`. + +## The Remade With Rust ecosystem + + + +**Remade With Rust** is an initiative by **[Mata Network](https://www.mata.network/)** +to rebuild essential C and C++ tools in Rust — for the memory safety, the +predictable performance, and the freedom of a permissive license. Each project +is a reimplementation, not a fork: same wire protocols and file formats, new +code you can actually depend on. No copyleft. No surprises. + +| Project | What it is | +|---|---| +| 🎬 **[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. | +| 🧠 **[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. | +| 🌐 **[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. | + +→ All projects: **[github.com/Remade-With-Rust](https://github.com/Remade-With-Rust)** + + + +## License + +BSD-2-Clause — see [LICENSE](https://github.com/remade-with-rust/rusty_h264/blob/main/LICENSE). diff --git a/vendor/rusty_h264-common/build.rs b/vendor/rusty_h264-common/build.rs new file mode 100644 index 0000000..d2335b7 --- /dev/null +++ b/vendor/rusty_h264-common/build.rs @@ -0,0 +1,18 @@ +//! Defines the internal `accel` cfg = "the `asm` feature is on AND we target x86_64". +//! +//! The vendored openh264 SIMD kernels in `rusty_h264-accel` are x86-64 only, so the +//! `accel` code paths must not be compiled on other architectures even when a downstream +//! crate enables the (default) `asm` feature. On non-x86_64 targets `accel` stays unset +//! and the codec uses its pure-Rust scalar path — so e.g. `rff` builds on arm64 macOS +//! with default features and without nasm. +fn main() { + // Declare the custom cfg so `unexpected_cfgs` (Rust 1.80+) stays quiet; older Cargo + // ignores the line (and lacks the lint anyway). + println!("cargo::rustc-check-cfg=cfg(accel)"); + let asm = std::env::var_os("CARGO_FEATURE_ASM").is_some(); + let x86_64 = std::env::var("CARGO_CFG_TARGET_ARCH").as_deref() == Ok("x86_64"); + if asm && x86_64 { + // Single-colon form: understood by every Cargo version. + println!("cargo:rustc-cfg=accel"); + } +} diff --git a/vendor/rusty_h264-common/examples/bs_layout_ceiling.rs b/vendor/rusty_h264-common/examples/bs_layout_ceiling.rs new file mode 100644 index 0000000..e4b77fa --- /dev/null +++ b/vendor/rusty_h264-common/examples/bs_layout_ceiling.rs @@ -0,0 +1,251 @@ +//! CEILING PROBE — is the bS derivation's 25x gap vs x264 really about LAYOUT? +//! +//! `docs/WHYS-decoder-perf.md` established: bS derivation is ~20% of decode at +//! ~400 ns/MB, against x264's `deblock_strength_avx2` at ~15 ns/MB, and the Step 0 +//! audit showed our derivation emits ZERO packed ops because `gather_tile` is a +//! gather — 24 blocks across 4-6 SEPARATE frame-wide arrays. +//! +//! The hypothesis is that x264 wins on LAYOUT (packed per-MB nnz bitmask + per-MB +//! contiguous ref/mv) and that the SIMD is downstream of it. That implies a large, +//! risky refactor of the decoder's macroblock loop, so PROVE THE CEILING FIRST: +//! measure the gather alone, current layout vs packed, with no decoder changes. +//! +//! The probe deliberately measures ONLY the gather. If packed-vs-strided is a small +//! ratio here, the refactor cannot pay however good a kernel sits behind it — and +//! that is a whole day saved for twenty minutes of probe. +//! +//! Also reports a DETERMINISTIC cache-line count, because this box cannot currently +//! resolve timing (see the noise-floor sections of the WHYS doc): the line count is +//! the part of the answer that machine load cannot touch. +//! +//! ```text +//! cargo run --release -p rusty_h264-common --example bs_layout_ceiling +//! ``` + +use std::hint::black_box; +use std::time::Instant; + +const MB_W: usize = 80; // 1280/16 +const MB_H: usize = 45; // 720/16 +const W4: usize = MB_W * 4; + +/// The CURRENT shape: separate frame-wide arrays, one per field. +struct Soa { + inter: Vec, + nnz: Vec, + mv: Vec<(i32, i32)>, + ref_id: Vec, +} + +/// The PACKED shape, mirroring x264's per-macroblock cache: everything one +/// macroblock's derivation needs, contiguous, in raster order. +/// +/// `nnz` collapses to a 16-BIT MASK — the derivation only ever asks "is this block +/// coded", never for the count — which is also what makes the coefficient half of +/// the strength test a shift-and-or on a single register instead of 32 byte loads. +#[derive(Clone, Copy, Default)] +#[repr(C, align(64))] +struct MbRec { + nnz_mask: u16, + inter: bool, + _pad: u8, + ref_id: [i16; 16], + mv: [(i16, i16); 16], +} + +fn build_soa() -> Soa { + let n = W4 * MB_H * 4; + // Deterministic pseudo-random content; a plausible mix of coded/uncoded and + // varying motion, so neither layout gets an unrealistically friendly pattern. + let mut s = 0x2545F491u32; + let mut rnd = move || { + s ^= s << 13; + s ^= s >> 17; + s ^= s << 5; + s + }; + let mut soa = + Soa { inter: vec![true; n], nnz: vec![0; n], mv: vec![(0, 0); n], ref_id: vec![0; n] }; + for i in 0..n { + let r = rnd(); + soa.inter[i] = (r & 0x1f) != 0; // ~3% intra + soa.nnz[i] = if (r >> 5) & 3 == 0 { 1 } else { 0 }; + soa.mv[i] = (((r >> 7) & 0x3f) as i32 - 32, ((r >> 13) & 0x3f) as i32 - 32); + soa.ref_id[i] = ((r >> 19) & 1) as i32; + } + soa +} + +fn build_packed(soa: &Soa) -> Vec { + let mut v = vec![MbRec::default(); MB_W * MB_H]; + for mb_y in 0..MB_H { + for mb_x in 0..MB_W { + let rec = &mut v[mb_y * MB_W + mb_x]; + let (bx0, by0) = (mb_x * 4, mb_y * 4); + rec.inter = soa.inter[by0 * W4 + bx0]; + for r in 0..4 { + for c in 0..4 { + let i = (by0 + r) * W4 + bx0 + c; + let k = r * 4 + c; + if soa.nnz[i] != 0 { + rec.nnz_mask |= 1 << k; + } + rec.ref_id[k] = soa.ref_id[i] as i16; + rec.mv[k] = (soa.mv[i].0 as i16, soa.mv[i].1 as i16); + } + } + } + } + v +} + +/// ARM A — the gather as it exists today: 24 blocks, each pulling from 4 separate +/// frame-wide arrays at a strided index. +#[inline(never)] +fn gather_strided(soa: &Soa, mb_x: usize, mb_y: usize) -> u64 { + let (bx0, by0) = (mb_x * 4, mb_y * 4); + let mut acc = 0u64; + let mut take = |i: usize| { + acc = acc + .wrapping_add(soa.inter[i] as u64) + .wrapping_add(soa.nnz[i] as u64) + .wrapping_add(soa.ref_id[i] as u64) + .wrapping_add(soa.mv[i].0 as u64) + .wrapping_add(soa.mv[i].1 as u64); + }; + for r in 0..4 { + for c in 0..4 { + take((by0 + r) * W4 + bx0 + c); + } + } + if mb_x > 0 { + for r in 0..4 { + take((by0 + r) * W4 + bx0 - 1); + } + } + if mb_y > 0 { + for c in 0..4 { + take((by0 - 1) * W4 + bx0 + c); + } + } + acc +} + +/// ARM B — the same information out of packed per-macroblock records: one +/// contiguous record for this macroblock plus the left and top neighbours'. +#[inline(never)] +fn gather_packed(recs: &[MbRec], mb_x: usize, mb_y: usize) -> u64 { + let cur = &recs[mb_y * MB_W + mb_x]; + let mut acc = cur.nnz_mask as u64 + cur.inter as u64; + for k in 0..16 { + acc = acc + .wrapping_add(cur.ref_id[k] as u64) + .wrapping_add(cur.mv[k].0 as u64) + .wrapping_add(cur.mv[k].1 as u64); + } + if mb_x > 0 { + let l = &recs[mb_y * MB_W + mb_x - 1]; + for r in 0..4 { + let k = r * 4 + 3; // right-hand column of the left neighbour + acc = acc + .wrapping_add(l.ref_id[k] as u64) + .wrapping_add(l.mv[k].0 as u64) + .wrapping_add(l.mv[k].1 as u64); + } + } + if mb_y > 0 { + let t = &recs[(mb_y - 1) * MB_W + mb_x]; + for c in 0..4 { + let k = 12 + c; // bottom row of the top neighbour + acc = acc + .wrapping_add(t.ref_id[k] as u64) + .wrapping_add(t.mv[k].0 as u64) + .wrapping_add(t.mv[k].1 as u64); + } + } + acc +} + +fn main() { + let soa = build_soa(); + let recs = build_packed(&soa); + let mbs = MB_W * MB_H; + + // ---- DETERMINISTIC part: distinct 64-byte cache lines touched per macroblock. + // Immune to machine load, which is why it leads. + let line = |addr: usize| addr / 64; + let mut a_lines = std::collections::HashSet::new(); + let mut b_lines = std::collections::HashSet::new(); + let (mb_x, mb_y) = (MB_W / 2, MB_H / 2); + let (bx0, by0) = (mb_x * 4, mb_y * 4); + let base = |p: *const u8| p as usize; + for r in 0..4 { + for c in 0..4 { + let i = (by0 + r) * W4 + bx0 + c; + a_lines.insert(line(base(soa.inter.as_ptr() as *const u8) + i)); + a_lines.insert(line(base(soa.nnz.as_ptr()) + i)); + a_lines.insert(line(base(soa.ref_id.as_ptr() as *const u8) + i * 4)); + a_lines.insert(line(base(soa.mv.as_ptr() as *const u8) + i * 8)); + } + } + let rec_base = base(recs.as_ptr() as *const u8) + (mb_y * MB_W + mb_x) * size_of::(); + for off in (0..size_of::()).step_by(64) { + b_lines.insert(line(rec_base + off)); + } + + println!("bS-derivation LAYOUT ceiling probe — 720p, {mbs} macroblocks\n"); + println!("DETERMINISTIC (machine load cannot move these):"); + println!(" MbRec size {:>6} bytes", size_of::()); + println!(" cache lines / MB, strided SoA {:>6} (own 16 blocks x 4 arrays)", a_lines.len()); + println!(" cache lines / MB, packed {:>6}", b_lines.len()); + println!( + " ratio {:>6.2}x fewer lines\n", + a_lines.len() as f64 / b_lines.len().max(1) as f64 + ); + + // ---- TIMED part: best-of-N, arms ABBA-alternated. Caveated on purpose. + let reps = 30; + let (mut best_a, mut best_b) = (f64::MAX, f64::MAX); + for rep in 0..reps { + let run_a = || { + let t = Instant::now(); + let mut acc = 0u64; + for y in 0..MB_H { + for x in 0..MB_W { + acc = acc.wrapping_add(gather_strided(black_box(&soa), x, y)); + } + } + (t.elapsed().as_secs_f64(), black_box(acc)) + }; + let run_b = || { + let t = Instant::now(); + let mut acc = 0u64; + for y in 0..MB_H { + for x in 0..MB_W { + acc = acc.wrapping_add(gather_packed(black_box(&recs), x, y)); + } + } + (t.elapsed().as_secs_f64(), black_box(acc)) + }; + // Alternate which arm runs first so warm-up bias cancels. + let (ta, tb) = if rep % 2 == 0 { + let (ta, _) = run_a(); + let (tb, _) = run_b(); + (ta, tb) + } else { + let (tb, _) = run_b(); + let (ta, _) = run_a(); + (ta, tb) + }; + best_a = best_a.min(ta); + best_b = best_b.min(tb); + } + let ns = |t: f64| t * 1e9 / mbs as f64; + println!("TIMED (best-of-{reps}, arms alternated — treat as INDICATIVE only;"); + println!(" this box has shown 45% within-arm spread under foreign load):"); + println!(" strided SoA gather {:>7.1} ns/MB", ns(best_a)); + println!(" packed gather {:>7.1} ns/MB", ns(best_b)); + println!(" ratio {:>7.2}x", best_a / best_b); + println!("\nFor scale: the whole derivation measures ~400 ns/MB in context;"); + println!("x264's deblock_strength_avx2 does the entire job in ~15 ns/MB."); +} diff --git a/vendor/rusty_h264-common/examples/deblock_anatomy.rs b/vendor/rusty_h264-common/examples/deblock_anatomy.rs new file mode 100644 index 0000000..d6f7aaa --- /dev/null +++ b/vendor/rusty_h264-common/examples/deblock_anatomy.rs @@ -0,0 +1,177 @@ +//! Deblock anatomy bench — isolates where `filter_frame` spends its time. +//! +//! Motivated by the video-tests function-level comparison, which put our +//! deblocking well behind x264's. x264 splits the work in two: boundary +//! strengths are derived in its MB-encode loop by an asm kernel +//! (`deblock_strength_avx2`, ~15 ns/MB measured in-context), and +//! `frame_deblock_row` only filters. Ours does both inside `filter_frame`, so a +//! stage-vs-stage read overstates the gap — and hides which half is actually slow. +//! +//! Four scenarios separate the two halves. The key one is `inter-bs0`: every +//! boundary strength derives to 0, so NO filter kernel runs and the number is +//! pure bS-derivation + loop glue. +//! +//! ```text +//! cargo run --release -p rusty_h264-common --features asm --example deblock_anatomy +//! ``` + +use rusty_h264_common::deblock::{filter_frame, BlockInfo}; + +struct Grid { + inter: Vec, + nnz: Vec, + mv: Vec<(i32, i32)>, + ref_id: Vec, + t8x8: Vec, +} + +const NO_REF: i32 = i32::MIN; + +/// Build the per-4×4-block state for one scenario. +fn grid(kind: &str, mb_w: usize, mb_h: usize) -> Grid { + let (w4, h4) = (mb_w * 4, mb_h * 4); + let n = w4 * h4; + let mut g = Grid { + inter: vec![true; n], + nnz: vec![0u8; n], + mv: vec![(0i32, 0i32); n], + ref_id: vec![0i32; n], + t8x8: Vec::new(), + }; + match kind { + // Every block intra: bS is 4 on MB edges, 3 internally — maximum + // filtering, and the bS derivation never reaches the motion comparison. + "all-intra" => { + g.inter.iter_mut().for_each(|b| *b = false); + g.ref_id.iter_mut().for_each(|r| *r = NO_REF); + } + // Every MB a skip: all inter, no coefficients, one shared (ref, mv). + // The flat-inter gate fires, so only MB edges are considered. + "skip" => {} + // Every block has coefficients: bS = 2 everywhere, so every edge filters. + "inter-coded" => { + g.nnz.iter_mut().for_each(|c| *c = 4); + } + // The isolator: all inter, no coefficients, motion that VARIES (so the + // flat-inter gate cannot fire) but by less than one full sample (so every + // bS still derives to 0 and no filter kernel runs). What remains is the + // bS derivation and the loop around it, and nothing else. + "inter-bs0" => { + for (i, m) in g.mv.iter_mut().enumerate() { + // ±1 quarter-pel: |Δ| < 4 for every neighbour pair ⇒ bS 0. + *m = ((i % 2) as i32, ((i / 2) % 2) as i32); + } + } + // Real content, unlike every scenario above, mixes intra/inter, coded and + // uncoded blocks, and varying motion WITHIN a macroblock — so the bS + // derivation's branches are unpredictable. The uniform scenarios let the + // predictor get every branch right, which is why they came in at ~240 + // ns/MB while real clips measure ~650. + "mixed" => { + let mut st = 0x12345678u32; + let mut rnd = || { + st ^= st << 13; + st ^= st >> 17; + st ^= st << 5; + st + }; + for i in 0..n { + let r = rnd(); + g.inter[i] = r & 7 != 0; // ~1 in 8 blocks intra + g.nnz[i] = if r & 0x30 != 0 { (r >> 8 & 7) as u8 } else { 0 }; + g.mv[i] = (((r >> 11) & 15) as i32 - 8, ((r >> 15) & 15) as i32 - 8); + g.ref_id[i] = if g.inter[i] { ((r >> 19) & 1) as i32 } else { NO_REF }; + } + } + _ => panic!("unknown scenario {kind}"), + } + g +} + +fn main() { + let cases = [(176usize, 144usize, "QCIF"), (352, 288, "CIF"), (1280, 720, "720p")]; + let scenarios = ["all-intra", "inter-coded", "inter-bs0", "skip", "mixed"]; + + println!("ns per macroblock, best-of-30 per arm, arms alternated pass by pass +"); + println!( + "{:<8} {:<12} {:>12} {:>12} {:>10}", + "size", "scenario", "branchy", "branchless", "speedup" + ); + println!("{}", "-".repeat(60)); + + for (w, h, label) in cases { + let (mb_w, mb_h) = (w / 16, h / 16); + let mbs = mb_w * mb_h; + let (cw, ch) = (w / 2, h / 2); + let mb_qp = vec![26u8; mbs]; + + for kind in scenarios { + let g = grid(kind, mb_w, mb_h); + // Content shaped like a real RECONSTRUCTION, not noise. The filter + // rejects an edge whose |p0-q0| >= alpha or |p1-p0| >= beta (~13/~6 at + // QP 26), so high-frequency synthetic data makes it early-out and the + // bench silently measures a filter that is barely running. A slow ramp + // with a small step at each 4-sample block boundary — exactly the + // blocking artefact deblocking exists to remove — keeps every edge + // inside the thresholds, so the kernels do their full work. + let px = |x: usize, yy: usize| -> u8 { + let ramp = 100 + ((x / 8 + yy / 8) % 24); + let step = ((x / 4) % 3) + ((yy / 4) % 2); // small block-edge discontinuity + (ramp + step) as u8 + }; + let y0: Vec = (0..w * h).map(|i| px(i % w, i / w)).collect(); + let u0: Vec = (0..cw * ch).map(|i| px(i % cw, i / cw)).collect(); + let v0: Vec = (0..cw * ch).map(|i| px((i % cw) + 3, i / cw)).collect(); + let (mut y, mut u, mut v) = (y0.clone(), u0.clone(), v0.clone()); + + // ALTERNATE the two bS arms pass by pass so both see the same + // thermal state; separate builds drift ~20% on this machine, which is + // larger than the effect being measured. + let mut best = [f64::MAX; 2]; + for pass in 0..60 { + let branchless = pass % 2 == 0; + rusty_h264_common::deblock::set_branchless_bs(branchless); + // CRITICAL: filter_frame smooths in place. Without restoring the + // source each pass, successive iterations run on progressively + // flatter data, the filter's α/β early-outs start firing, and + // best-of-N reports the cheapest (most-smoothed) pass rather than + // the real cost. Restore outside the timed region. + y.copy_from_slice(&y0); + u.copy_from_slice(&u0); + v.copy_from_slice(&v0); + let info = BlockInfo { + inter: &g.inter, + nnz: &g.nnz, + mv: &g.mv, + ref_id: &g.ref_id, + mv1: &[], + ref_id1: &[], + w4: mb_w * 4, + t8x8: &g.t8x8, + poc0: &[], + poc1: &[], + bs: &[], kind: &[], + }; + let t = std::time::Instant::now(); + filter_frame(&mut y, &mut u, &mut v, mb_w, mb_h, &mb_qp, 0, 0, 0, &info); + let e = t.elapsed().as_secs_f64(); + let slot = if branchless { 0 } else { 1 }; + if e < best[slot] { + best[slot] = e; + } + std::hint::black_box((&y, &u, &v)); + } + let ns = |t: f64| t * 1e9 / mbs as f64; + println!( + "{:<8} {:<12} {:>12.1} {:>12.1} {:>9.2}x", + label, + kind, + ns(best[1]), + ns(best[0]), + ns(best[1]) / ns(best[0]) + ); + } + println!(); + } +} diff --git a/vendor/rusty_h264-common/src/aligned.rs b/vendor/rusty_h264-common/src/aligned.rs new file mode 100644 index 0000000..c8e71be --- /dev/null +++ b/vendor/rusty_h264-common/src/aligned.rs @@ -0,0 +1,55 @@ +//! A 16-byte-aligned heap byte buffer for the openh264 spatial asm kernels. +//! +//! openh264's deblock / MC / intra-prediction asm load aligned 16-byte row chunks +//! (`movdqa`), which a plain `Vec` (alignment 1) cannot satisfy. [`AlignedBytes`] +//! is backed by a `Vec` (alignment 16) and viewed as `[u8]` through `bytemuck` +//! — guaranteed 16-aligned, no `unsafe`. It `Deref`s to `[u8]`, so it is a drop-in for +//! the reconstruction / reference plane buffers (`FrameEncoder` rec planes, `RefFrame`). + +use std::ops::{Deref, DerefMut}; + +/// A heap byte buffer guaranteed to start on a 16-byte boundary. +#[derive(Clone, Default)] +pub struct AlignedBytes { + words: Vec, + len: usize, +} + +impl AlignedBytes { + /// A zero-filled, 16-byte-aligned buffer of `len` bytes. + pub fn zeroed(len: usize) -> Self { + Self { + words: vec![0u128; (len + 15) / 16], + len, + } + } + + pub fn len(&self) -> usize { + self.len + } + + pub fn is_empty(&self) -> bool { + self.len == 0 + } +} + +impl std::fmt::Debug for AlignedBytes { + fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + write!(f, "AlignedBytes({} bytes)", self.len) + } +} + +impl Deref for AlignedBytes { + type Target = [u8]; + #[inline] + fn deref(&self) -> &[u8] { + &bytemuck::cast_slice(&self.words)[..self.len] + } +} + +impl DerefMut for AlignedBytes { + #[inline] + fn deref_mut(&mut self) -> &mut [u8] { + &mut bytemuck::cast_slice_mut(&mut self.words)[..self.len] + } +} diff --git a/vendor/rusty_h264-common/src/bit_reader.rs b/vendor/rusty_h264-common/src/bit_reader.rs new file mode 100644 index 0000000..c67a25c --- /dev/null +++ b/vendor/rusty_h264-common/src/bit_reader.rs @@ -0,0 +1,343 @@ +//! MSB-first bit reader with H.264 Exp-Golomb decoding. +//! +//! The inverse of [`crate::BitWriter`]. Operates over an RBSP byte slice +//! (emulation-prevention bytes already removed — see [`crate::nal`]). + +/// Error returned when a read runs past the end of the buffer. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub struct OutOfData; + +impl core::fmt::Display for OutOfData { + fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result { + f.write_str("bit reader ran out of data") + } +} + +impl std::error::Error for OutOfData {} + +/// A big-endian, MSB-first bit reader. +#[derive(Debug, Clone)] +pub struct BitReader<'a> { + data: &'a [u8], + /// Absolute bit position from the start of `data`. + pos: usize, +} + +impl<'a> BitReader<'a> { + /// Wraps an RBSP byte slice. + pub fn new(data: &'a [u8]) -> Self { + Self { data, pos: 0 } + } + + /// The underlying RBSP buffer (for handing off to the CABAC engine). + pub fn data(&self) -> &'a [u8] { + self.data + } + + /// Current bit position. + pub fn bit_pos(&self) -> usize { + self.pos + } + + /// Total number of bits in the buffer. + pub fn bit_len(&self) -> usize { + self.data.len() * 8 + } + + /// Bits remaining. + pub fn bits_left(&self) -> usize { + self.bit_len().saturating_sub(self.pos) + } + + /// `more_rbsp_data()` (spec §7.2): true while the read position is before the + /// `rbsp_stop_one_bit` (the last set bit in the buffer). Used to detect the + /// end of `slice_data()` when a picture is split into multiple slices. + pub fn more_rbsp_data(&self) -> bool { + // Stop bit = the last 1 bit in the buffer; in MSB-first order that is the + // lowest set bit of the last non-zero byte. + let stop = self + .data + .iter() + .enumerate() + .rev() + .find(|(_, &b)| b != 0) + .map(|(bi, &b)| bi * 8 + (7 - b.trailing_zeros() as usize)); + match stop { + Some(s) => self.pos < s, + None => false, + } + } + + /// `true` if the read position sits on a byte boundary. + pub fn is_byte_aligned(&self) -> bool { + self.pos % 8 == 0 + } + + /// Advances to the next byte boundary, consuming the intervening bits (e.g. + /// `pcm_alignment_zero_bit`s before an `I_PCM` payload). + pub fn align_to_byte(&mut self) -> Result<(), OutOfData> { + while self.pos % 8 != 0 { + self.read_bit()?; + } + Ok(()) + } + + /// Reads a single bit. + pub fn read_bit(&mut self) -> Result { + if self.pos >= self.bit_len() { + return Err(OutOfData); + } + let byte = self.data[self.pos / 8]; + let bit = (byte >> (7 - (self.pos % 8))) & 1; + self.pos += 1; + Ok(bit == 1) + } + + /// Reads `n` bits (`n` <= 32) as an unsigned value, MSB first. `u(n)`. + pub fn read_bits(&mut self, n: u32) -> Result { + // More than 32 bits cannot fit a u32. Rather than panic on a hostile + // length (e.g. a corrupt log2_* field driving the count), reject it. + if n > 32 { + return Err(OutOfData); + } + if n == 0 { + return Ok(0); + } + if n <= 24 { + let v = self.peek_bits(n); + self.skip_bits(n)?; + return Ok(v); + } + // n in 25..=32: two chunks (peek_bits caps at 24). + let hi = self.read_bits(n - 16)?; + let lo = self.read_bits(16)?; + Ok((hi << 16) | lo) + } + + /// Peeks the next `n` bits (`n` ≤ 24) as an MSB-first value **without + /// consuming**, zero-filling past the end of the buffer. O(1): loads up to 4 + /// bytes. The zero-fill lets a VLC/Exp-Golomb table match be attempted at the + /// stream end; the caller then [`skip_bits`](Self::skip_bits)s the matched + /// length, which rejects (OutOfData) if those bits ran past the buffer. + #[inline] + pub fn peek_bits(&self, n: u32) -> u32 { + debug_assert!(n <= 24); + let byte = self.pos / 8; + let off = (self.pos % 8) as u32; + // 4 bytes (zero past end), MSB-first, into a 32-bit window. + // + // FAST PATH: one RANGE check and one 4-byte big-endian load, which LLVM + // lowers to `mov` + `bswap`. The previous form did FOUR separate + // bounds-checked `get().unwrap_or(&0)` loads plus three shifts and three ORs, + // on a function the entropy decoder calls tens of millions of times per + // sequence. No `unsafe` needed — `get(range)` + `from_be_bytes` is safe and + // compiles to the same thing an unchecked load would. + // + // The slow arm keeps the EXACT zero-fill-past-the-end contract the doc + // comment promises (and that VLC matching at stream end relies on), so the + // two arms are indistinguishable to every caller; `peek_bits_tail_matches` + // pins that across the whole boundary region. + let acc = match self.data.get(byte..byte + 4) { + Some(c) => u32::from_be_bytes([c[0], c[1], c[2], c[3]]), + None => { + ((*self.data.get(byte).unwrap_or(&0) as u32) << 24) + | ((*self.data.get(byte + 1).unwrap_or(&0) as u32) << 16) + | ((*self.data.get(byte + 2).unwrap_or(&0) as u32) << 8) + | (*self.data.get(byte + 3).unwrap_or(&0) as u32) + } + }; + // The bit at `pos` is window bit (31 − off); take the `n` bits below it. + (acc >> (32 - off - n)) & ((1u32 << n) - 1) + } + + /// Consumes `n` bits (advances the position), after a [`peek_bits`]. Rejects + /// if the bits run past the end of the buffer — the truncated-stream guard + /// that `read_bit`'s per-bit bounds check provided. + #[inline] + pub fn skip_bits(&mut self, n: u32) -> Result<(), OutOfData> { + if self.pos + n as usize > self.bit_len() { + return Err(OutOfData); + } + self.pos += n as usize; + Ok(()) + } + + /// Unsigned Exp-Golomb decode, `ue(v)`. + pub fn read_ue(&mut self) -> Result { + // Fast path: a codeword with `lz` leading zeros is `2·lz+1` bits. With + // `lz ≤ 11` the whole codeword fits the 24-bit peek window — find `lz` + // by counting leading zeros, then extract value in one shot. + let window = self.peek_bits(24); + let lz = window.leading_zeros() - 8; // leading zeros within the 24-bit window + if lz <= 11 { + let total = 2 * lz + 1; + self.skip_bits(total)?; + if lz == 0 { + return Ok(0); + } + let info = (window >> (24 - total)) & ((1u32 << lz) - 1); + return Ok((1u32 << lz) - 1 + info); + } + // ≥12 leading zeros (huge value or run of zeros): exact bit-at-a-time. + let mut leading_zeros = 0u32; + while !self.read_bit()? { + leading_zeros += 1; + // 32 leading zeros would make `1 << leading_zeros` overflow u32 (and + // the value is not representable anyway) — reject as malformed. + if leading_zeros >= 32 { + return Err(OutOfData); + } + } + if leading_zeros == 0 { + return Ok(0); + } + let info = self.read_bits(leading_zeros)?; + Ok((1u32 << leading_zeros) - 1 + info) + } + + /// Signed Exp-Golomb decode, `se(v)`. + pub fn read_se(&mut self) -> Result { + let code_num = self.read_ue()?; + // Inverse of the se->code_num mapping. + let magnitude = code_num.div_ceil(2) as i32; + Ok(if code_num % 2 == 1 { magnitude } else { -magnitude }) + } +} + +#[cfg(test)] +mod tests { + use super::*; + use crate::BitWriter; + +/// The one-load fast path must equal the byte-at-a-time zero-fill reference at + /// EVERY bit position and width — including the last bytes, where the fast arm + /// stops applying and the tail arm takes over. A mismatch there would corrupt + /// VLC matching only at stream end, which is exactly the bug a mid-buffer test + /// would miss. + #[test] + fn peek_bits_matches_zero_fill_reference() { + fn reference(data: &[u8], pos: usize, n: u32) -> u32 { + let byte = pos / 8; + let off = (pos % 8) as u32; + let acc = ((*data.get(byte).unwrap_or(&0) as u32) << 24) + | ((*data.get(byte + 1).unwrap_or(&0) as u32) << 16) + | ((*data.get(byte + 2).unwrap_or(&0) as u32) << 8) + | (*data.get(byte + 3).unwrap_or(&0) as u32); + (acc >> (32 - off - n)) & ((1u32 << n) - 1) + } + let mut st = 0x1234_5678u32; + let mut rnd = || { + st ^= st << 13; + st ^= st >> 17; + st ^= st << 5; + st + }; + for len in 1..24usize { + let data: Vec = (0..len).map(|_| (rnd() >> 7) as u8).collect(); + let r = BitReader::new(&data); + for pos in 0..len * 8 { + for n in 1..=24u32 { + let mut br = BitReader::new(&data); + br.skip_bits(pos as u32).ok(); + // skip_bits refuses past the end; drive `pos` directly instead. + let mut probe = BitReader::new(&data); + while probe.bit_pos() < pos { + if probe.read_bit().is_err() { + break; + } + } + if probe.bit_pos() != pos { + continue; + } + assert_eq!( + probe.peek_bits(n), + reference(&data, pos, n), + "len={len} pos={pos} n={n}" + ); + } + } + let _ = r; + } + } + + #[test] + fn roundtrip_ue() { + for v in [0u32, 1, 2, 3, 4, 7, 8, 255, 256, 65535, u32::MAX - 1] { + let mut w = BitWriter::new(); + w.write_ue(v); + w.align_zero(); + let bytes = w.into_bytes(); + let mut r = BitReader::new(&bytes); + assert_eq!(r.read_ue().unwrap(), v, "ue roundtrip {v}"); + } + } + + #[test] + fn roundtrip_se() { + for v in [0i32, 1, -1, 2, -2, 100, -100, 32767, -32768] { + let mut w = BitWriter::new(); + w.write_se(v); + w.align_zero(); + let bytes = w.into_bytes(); + let mut r = BitReader::new(&bytes); + assert_eq!(r.read_se().unwrap(), v, "se roundtrip {v}"); + } + } + + #[test] + fn roundtrip_mixed_stream() { + let mut w = BitWriter::new(); + w.write_bits(0b1011, 4); + w.write_ue(42); + w.write_se(-17); + w.write_bits(1, 1); + w.align_zero(); + let bytes = w.into_bytes(); + + let mut r = BitReader::new(&bytes); + assert_eq!(r.read_bits(4).unwrap(), 0b1011); + assert_eq!(r.read_ue().unwrap(), 42); + assert_eq!(r.read_se().unwrap(), -17); + assert_eq!(r.read_bits(1).unwrap(), 1); + } + + #[test] + fn reports_out_of_data() { + let bytes = [0x80u8]; + let mut r = BitReader::new(&bytes); + assert_eq!(r.read_bits(8).unwrap(), 0x80); + assert_eq!(r.read_bit(), Err(OutOfData)); + } + + #[test] + fn peek_then_skip_matches_read_bits() { + let bytes = [0xB5u8, 0x3C, 0xF0, 0x0A, 0x77]; + // At every bit offset and width, peek_bits + skip_bits must equal a + // consuming read_bits from a fresh reader at the same position. + for start in 0..16u32 { + for n in 1..=24u32 { + let mut a = BitReader::new(&bytes); + a.skip_bits(start).unwrap(); + let peeked = a.peek_bits(n); + let pos_before = a.bit_pos(); + a.skip_bits(n).unwrap(); + assert_eq!(a.bit_pos(), pos_before + n as usize); + + let mut b = BitReader::new(&bytes); + b.skip_bits(start).unwrap(); + assert_eq!(peeked, b.read_bits(n).unwrap(), "start={start} n={n}"); + } + } + } + + #[test] + fn peek_zero_fills_past_end() { + let bytes = [0xFFu8]; + let mut r = BitReader::new(&bytes); + r.skip_bits(4).unwrap(); + // 4 real bits (1111) then zero-fill: 0b1111_0000_0000... for 12 bits. + assert_eq!(r.peek_bits(12), 0b1111_0000_0000); + // skipping past the end is rejected. + assert_eq!(r.skip_bits(8), Err(OutOfData)); + } +} diff --git a/vendor/rusty_h264-common/src/bit_writer.rs b/vendor/rusty_h264-common/src/bit_writer.rs new file mode 100644 index 0000000..5ed8797 --- /dev/null +++ b/vendor/rusty_h264-common/src/bit_writer.rs @@ -0,0 +1,319 @@ +//! MSB-first bit writer with H.264 Exp-Golomb coding. +//! +//! H.264 packs syntax elements as a big-endian bitstream: the first bit written +//! lands in the most-significant position of the first byte. This writer +//! accumulates bits and exposes the Exp-Golomb (`ue`/`se`) and fixed-length +//! (`u`) codings the bitstream syntax is built from. + +/// A growable, MSB-first bit buffer. +/// +/// Uses a **bit cache**: bits accumulate in the low `nbits` positions of a 64-bit +/// `cache` (the most-recently-written bit is least-significant within the valid +/// region), and whole bytes are flushed off the top. A multi-bit write is a shift +/// + OR + a short byte-flush loop — not one operation per bit. After every public +/// write the invariant `nbits < 8` and "bits above `nbits` are zero" hold. +#[derive(Debug, Default, Clone)] +pub struct BitWriter { + /// Completed bytes. + bytes: Vec, + /// Pending bits, valid in the low `nbits` positions (zero above). + cache: u64, + /// Number of valid pending bits (0..=7 between writes). + nbits: u32, +} + +impl BitWriter { + /// Creates an empty writer. + pub fn new() -> Self { + Self::default() + } + + /// Creates a writer with `bytes` pre-reserved — for the per-frame slice writer, + /// so the CAVLC hot loop never pays a `Vec` realloc mid-frame. + pub fn with_capacity(bytes: usize) -> Self { + Self { + bytes: Vec::with_capacity(bytes), + cache: 0, + nbits: 0, + } + } + + /// Number of bits written so far. + pub fn bit_len(&self) -> usize { + self.bytes.len() * 8 + self.nbits as usize + } + + /// `true` if the writer is on a byte boundary. + pub fn is_byte_aligned(&self) -> bool { + self.nbits % 8 == 0 + } + + /// Writes the low `n` bits of `value`, most-significant first (`u(n)`). `n` <= 32. + /// + /// Keeps up to 31 pending bits in `cache` and flushes a whole **u32 word** (4 + /// bytes) at a time, like openh264's `BsWriteBits` (`WRITE_BE_32`) — a quarter + /// the `Vec` writes of byte-at-a-time flushing. + #[inline] + pub fn write_bits(&mut self, value: u32, n: u32) { + debug_assert!(n <= 32, "write_bits supports up to 32 bits"); + if n == 0 { + return; + } + let mask = (1u64 << n) - 1; // n<=32 so 1<<32 fits u64 + self.cache = (self.cache << n) | (value as u64 & mask); + self.nbits += n; + if self.nbits >= 32 { + self.nbits -= 32; + let word = (self.cache >> self.nbits) as u32; + self.bytes.extend_from_slice(&word.to_be_bytes()); + self.cache &= (1u64 << self.nbits) - 1; // drop the flushed high bits + } + } + + /// Writes a single bit (`true` => 1). + #[inline] + pub fn write_bit(&mut self, bit: bool) { + self.write_bits(bit as u32, 1); + } + + /// Appends every bit of `other`, in order, at this writer's current position. + /// + /// Neither writer need be byte-aligned. This is what lets a macroblock be + /// encoded into a scratch writer *before* the syntax that must precede it is + /// known (`mb_skip_run` is only decided once the macroblock's own cost is), so + /// the encoder can commit one encode rather than trialing and repeating it. + /// Sound for CAVLC because a macroblock's Exp-Golomb/VLC syntax does not depend + /// on its bit position; an arithmetic coder (CABAC) could NOT be spliced this + /// way, since its state is carried across the whole slice. + pub fn append(&mut self, other: &BitWriter) { + for chunk in other.bytes.chunks(4) { + let mut word = 0u32; + for &b in chunk { + word = (word << 8) | b as u32; + } + self.write_bits(word, chunk.len() as u32 * 8); + } + if other.nbits > 0 { + // `cache` holds `nbits` (<= 31) valid bits in its low positions. + self.write_bits(other.cache as u32, other.nbits); + } + } + + /// Emits a value already mapped to its Exp-Golomb code number: `floor(log2 x)` + /// leading zeros then `x` in `floor(log2 x)+1` bits, where `x = code_num + 1`. + #[inline] + fn put_golomb(&mut self, x: u64) { + let n = 63 - x.leading_zeros(); // floor(log2 x), 0..=32 + self.write_bits(0, n); + if n < 32 { + self.write_bits(x as u32, n + 1); + } else { + // n == 32 (e.g. ue(u32::MAX)): 33-bit value, split across two writes. + self.write_bits((x >> 32) as u32, n - 31); + self.write_bits(x as u32, 32); + } + } + + /// Unsigned Exp-Golomb code `ue(v)`. + pub fn write_ue(&mut self, value: u32) { + self.put_golomb(value as u64 + 1); + } + + /// Signed Exp-Golomb code `se(v)`: `0->0, 1->1, -1->2, 2->3, -2->4, ...`. + pub fn write_se(&mut self, value: i32) { + let code_num = if value <= 0 { + (-(value as i64) as u64) * 2 + } else { + (value as u64) * 2 - 1 + }; + self.put_golomb(code_num + 1); + } + + /// Writes the `rbsp_trailing_bits()`: a stop bit `1` then zero-pad to a byte. + pub fn rbsp_trailing_bits(&mut self) { + self.write_bits(1, 1); + self.align_zero(); + } + + /// Pads with zero bits to the next byte boundary (no stop bit), then flushes + /// the pending whole bytes from the cache (the word-flush in `write_bits` can + /// leave up to 31 pending bits). + pub fn align_zero(&mut self) { + let pad = (8 - self.nbits % 8) % 8; + if pad != 0 { + self.write_bits(0, pad); + } + while self.nbits >= 8 { + self.nbits -= 8; + self.bytes.push((self.cache >> self.nbits) as u8); + } + self.cache = 0; + } + + /// Consumes the writer, returning the byte buffer. Flushes any whole bytes + /// still pending in the cache; panics if a sub-byte remainder is left (call + /// [`rbsp_trailing_bits`](Self::rbsp_trailing_bits) or + /// [`align_zero`](Self::align_zero) first). + pub fn into_bytes(mut self) -> Vec { + while self.nbits >= 8 { + self.nbits -= 8; + self.bytes.push((self.cache >> self.nbits) as u8); + } + assert!( + self.nbits == 0, + "BitWriter::into_bytes called with {} dangling bits", + self.nbits + ); + self.bytes + } + + /// Borrows the completed bytes (excludes bits still pending in the cache). + pub fn as_bytes(&self) -> &[u8] { + &self.bytes + } +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn write_bits_is_msb_first() { + let mut w = BitWriter::new(); + w.write_bits(0b101, 3); + w.write_bits(0b1, 1); + w.align_zero(); + // bits 1,0,1,1 then zero-pad -> 1011_0000 + assert_eq!(w.into_bytes(), vec![0b1011_0000]); + } + + #[test] + fn ue_known_values() { + // From H.264 Table 9-2: code_num -> bit string. + let cases: &[(u32, &str)] = &[ + (0, "1"), + (1, "010"), + (2, "011"), + (3, "00100"), + (4, "00101"), + (5, "00110"), + (6, "00111"), + (7, "0001000"), + (8, "0001001"), + ]; + for &(v, bits) in cases { + let mut w = BitWriter::new(); + w.write_ue(v); + assert_eq!(bitstring(&w), bits, "ue({v})"); + } + } + + #[test] + fn se_known_values() { + // H.264 Table 9-3 mapping: se -> code_num. + let cases: &[(i32, &str)] = &[ + (0, "1"), // code_num 0 + (1, "010"), // 1 + (-1, "011"), // 2 + (2, "00100"), + (-2, "00101"), + (3, "00110"), + (-3, "00111"), + ]; + for &(v, bits) in cases { + let mut w = BitWriter::new(); + w.write_se(v); + assert_eq!(bitstring(&w), bits, "se({v})"); + } + } + + #[test] + fn ue_max_does_not_overflow() { + let mut w = BitWriter::new(); + w.write_ue(u32::MAX); + // value+1 = 2^32 -> 32 leading zeros then 33-bit value => 65 bits total. + assert_eq!(w.bit_len(), 65); + } + + #[test] + fn rbsp_trailing_aligns_to_byte() { + let mut w = BitWriter::new(); + w.write_bits(0b101, 3); + w.rbsp_trailing_bits(); + // 101 + stop 1 + pad 0000 => 1011_0000 + assert_eq!(w.into_bytes(), vec![0b1011_0000]); + } + + /// Renders the bits currently buffered (including the partial byte) as a + /// string of '0'/'1' for assertions. + fn bitstring(w: &BitWriter) -> String { + let mut s = String::new(); + for &b in w.as_bytes() { + for i in (0..8).rev() { + s.push(if (b >> i) & 1 == 1 { '1' } else { '0' }); + } + } + for i in (0..w.nbits).rev() { + s.push(if (w.cache >> i) & 1 == 1 { '1' } else { '0' }); + } + s + } +} + +#[cfg(test)] +mod append_tests { + use super::BitWriter; + + /// Appending must be indistinguishable from having written the bits inline, + /// at every source/destination bit misalignment — this is the invariant the + /// encoder's encode-once-and-splice path rests on. + #[test] + fn append_matches_inline_at_every_alignment() { + for lead in 0..17u32 { + for n in 0..40u32 { + let mut inline = BitWriter::new(); + inline.write_bits(0b1011_0110, lead.min(8)); + if lead > 8 { + inline.write_bits(0x5A5A, lead - 8); + } + let mut spliced = inline.clone(); + + // the payload, written bit-patterned so order errors show up + let mut scratch = BitWriter::new(); + for i in 0..n { + scratch.write_bit(i % 3 == 0); + } + for i in 0..n { + inline.write_bit(i % 3 == 0); + } + spliced.append(&scratch); + + assert_eq!(spliced.bit_len(), inline.bit_len(), "lead={lead} n={n}: length"); + let (mut a, mut b) = (spliced.clone(), inline.clone()); + a.align_zero(); + b.align_zero(); + assert_eq!(a.into_bytes(), b.into_bytes(), "lead={lead} n={n}: bits"); + } + } + } + + /// Exp-Golomb payloads across a byte-crossing boundary (the real shape). + #[test] + fn append_preserves_exp_golomb() { + for lead in 0..9u32 { + let mut inline = BitWriter::new(); + inline.write_bits(1, lead); + let mut spliced = inline.clone(); + let mut scratch = BitWriter::new(); + for v in [0u32, 1, 7, 40, 1000, 65535] { + scratch.write_ue(v); + inline.write_ue(v); + } + spliced.append(&scratch); + assert_eq!(spliced.bit_len(), inline.bit_len(), "lead={lead}: length"); + spliced.align_zero(); + inline.align_zero(); + assert_eq!(spliced.into_bytes(), inline.into_bytes(), "lead={lead}"); + } + } +} diff --git a/vendor/rusty_h264-common/src/cabac_tables.rs b/vendor/rusty_h264-common/src/cabac_tables.rs new file mode 100644 index 0000000..92f58ca --- /dev/null +++ b/vendor/rusty_h264-common/src/cabac_tables.rs @@ -0,0 +1,644 @@ +//! CABAC tables ported verbatim from openh264 `common_tables.cpp` (spec +//! Tables 9-44/9-45 and 9-12..9-33). 460 contexts, 4 init models [I,idc0,idc1,idc2]. +//! `CTX_NA` sentinels (I-slice-unused contexts) are 0 as in openh264. + +/// `rangeTabLPS[pStateIdx][(range>>6)&3]` (Table 9-44). +pub const RANGE_LPS: [[u8; 4]; 64] = [ + [128, 176, 208, 240], + [128, 167, 197, 227], + [128, 158, 187, 216], + [123, 150, 178, 205], + [116, 142, 169, 195], + [111, 135, 160, 185], + [105, 128, 152, 175], + [100, 122, 144, 166], + [95, 116, 137, 158], + [90, 110, 130, 150], + [85, 104, 123, 142], + [81, 99, 117, 135], + [77, 94, 111, 128], + [73, 89, 105, 122], + [69, 85, 100, 116], + [66, 80, 95, 110], + [62, 76, 90, 104], + [59, 72, 86, 99], + [56, 69, 81, 94], + [53, 65, 77, 89], + [51, 62, 73, 85], + [48, 59, 69, 80], + [46, 56, 66, 76], + [43, 53, 63, 72], + [41, 50, 59, 69], + [39, 48, 56, 65], + [37, 45, 54, 62], + [35, 43, 51, 59], + [33, 41, 48, 56], + [32, 39, 46, 53], + [30, 37, 43, 50], + [29, 35, 41, 48], + [27, 33, 39, 45], + [26, 31, 37, 43], + [24, 30, 35, 41], + [23, 28, 33, 39], + [22, 27, 32, 37], + [21, 26, 30, 35], + [20, 24, 29, 33], + [19, 23, 27, 31], + [18, 22, 26, 30], + [17, 21, 25, 28], + [16, 20, 23, 27], + [15, 19, 22, 25], + [14, 18, 21, 24], + [14, 17, 20, 23], + [13, 16, 19, 22], + [12, 15, 18, 21], + [12, 14, 17, 20], + [11, 14, 16, 19], + [11, 13, 15, 18], + [10, 12, 15, 17], + [10, 12, 14, 16], + [9, 11, 13, 15], + [9, 11, 12, 14], + [8, 10, 12, 14], + [8, 9, 11, 13], + [7, 9, 11, 12], + [7, 9, 10, 12], + [7, 8, 10, 11], + [6, 8, 9, 11], + [6, 7, 9, 10], + [6, 7, 8, 9], + [2, 2, 2, 2], +]; + +/// State transition `[pStateIdx] -> [transIdxLPS, transIdxMPS]` (Table 9-45). +pub const STATE_TRANS: [[u8; 2]; 64] = [ + [0, 1], + [0, 2], + [1, 3], + [2, 4], + [2, 5], + [4, 6], + [4, 7], + [5, 8], + [6, 9], + [7, 10], + [8, 11], + [9, 12], + [9, 13], + [11, 14], + [11, 15], + [12, 16], + [13, 17], + [13, 18], + [15, 19], + [15, 20], + [16, 21], + [16, 22], + [18, 23], + [18, 24], + [19, 25], + [19, 26], + [21, 27], + [21, 28], + [22, 29], + [22, 30], + [23, 31], + [24, 32], + [24, 33], + [25, 34], + [26, 35], + [26, 36], + [27, 37], + [27, 38], + [28, 39], + [29, 40], + [29, 41], + [30, 42], + [30, 43], + [30, 44], + [31, 45], + [32, 46], + [32, 47], + [33, 48], + [33, 49], + [33, 50], + [34, 51], + [34, 52], + [35, 53], + [35, 54], + [35, 55], + [36, 56], + [36, 57], + [36, 58], + [37, 59], + [37, 60], + [37, 61], + [38, 62], + [38, 62], + [63, 63], +]; + +/// Context init `(m, n)` per `[ctxIdx][model]` (model 0=I, 1..=3 = init_idc 0..2). +pub const CTX_INIT: [[(i16, i16); 4]; 460] = [ + [(20, -15), (20, -15), (20, -15), (20, -15)], + [(2, 54), (2, 54), (2, 54), (2, 54)], + [(3, 74), (3, 74), (3, 74), (3, 74)], + [(20, -15), (20, -15), (20, -15), (20, -15)], + [(2, 54), (2, 54), (2, 54), (2, 54)], + [(3, 74), (3, 74), (3, 74), (3, 74)], + [(-28, 127), (-28, 127), (-28, 127), (-28, 127)], + [(-23, 104), (-23, 104), (-23, 104), (-23, 104)], + [(-6, 53), (-6, 53), (-6, 53), (-6, 53)], + [(-1, 54), (-1, 54), (-1, 54), (-1, 54)], + [(7, 51), (7, 51), (7, 51), (7, 51)], + [(0, 0), (23, 33), (22, 25), (29, 16)], + [(0, 0), (23, 2), (34, 0), (25, 0)], + [(0, 0), (21, 0), (16, 0), (14, 0)], + [(0, 0), (1, 9), (-2, 9), (-10, 51)], + [(0, 0), (0, 49), (4, 41), (-3, 62)], + [(0, 0), (-37, 118), (-29, 118), (-27, 99)], + [(0, 0), (5, 57), (2, 65), (26, 16)], + [(0, 0), (-13, 78), (-6, 71), (-4, 85)], + [(0, 0), (-11, 65), (-13, 79), (-24, 102)], + [(0, 0), (1, 62), (5, 52), (5, 57)], + [(0, 0), (12, 49), (9, 50), (6, 57)], + [(0, 0), (-4, 73), (-3, 70), (-17, 73)], + [(0, 0), (17, 50), (10, 54), (14, 57)], + [(0, 0), (18, 64), (26, 34), (20, 40)], + [(0, 0), (9, 43), (19, 22), (20, 10)], + [(0, 0), (29, 0), (40, 0), (29, 0)], + [(0, 0), (26, 67), (57, 2), (54, 0)], + [(0, 0), (16, 90), (41, 36), (37, 42)], + [(0, 0), (9, 104), (26, 69), (12, 97)], + [(0, 0), (-46, 127), (-45, 127), (-32, 127)], + [(0, 0), (-20, 104), (-15, 101), (-22, 117)], + [(0, 0), (1, 67), (-4, 76), (-2, 74)], + [(0, 0), (-13, 78), (-6, 71), (-4, 85)], + [(0, 0), (-11, 65), (-13, 79), (-24, 102)], + [(0, 0), (1, 62), (5, 52), (5, 57)], + [(0, 0), (-6, 86), (6, 69), (-6, 93)], + [(0, 0), (-17, 95), (-13, 90), (-14, 88)], + [(0, 0), (-6, 61), (0, 52), (-6, 44)], + [(0, 0), (9, 45), (8, 43), (4, 55)], + [(0, 0), (-3, 69), (-2, 69), (-11, 89)], + [(0, 0), (-6, 81), (-5, 82), (-15, 103)], + [(0, 0), (-11, 96), (-10, 96), (-21, 116)], + [(0, 0), (6, 55), (2, 59), (19, 57)], + [(0, 0), (7, 67), (2, 75), (20, 58)], + [(0, 0), (-5, 86), (-3, 87), (4, 84)], + [(0, 0), (2, 88), (-3, 100), (6, 96)], + [(0, 0), (0, 58), (1, 56), (1, 63)], + [(0, 0), (-3, 76), (-3, 74), (-5, 85)], + [(0, 0), (-10, 94), (-6, 85), (-13, 106)], + [(0, 0), (5, 54), (0, 59), (5, 63)], + [(0, 0), (4, 69), (-3, 81), (6, 75)], + [(0, 0), (-3, 81), (-7, 86), (-3, 90)], + [(0, 0), (0, 88), (-5, 95), (-1, 101)], + [(0, 0), (-7, 67), (-1, 66), (3, 55)], + [(0, 0), (-5, 74), (-1, 77), (-4, 79)], + [(0, 0), (-4, 74), (1, 70), (-2, 75)], + [(0, 0), (-5, 80), (-2, 86), (-12, 97)], + [(0, 0), (-7, 72), (-5, 72), (-7, 50)], + [(0, 0), (1, 58), (0, 61), (1, 60)], + [(0, 41), (0, 41), (0, 41), (0, 41)], + [(0, 63), (0, 63), (0, 63), (0, 63)], + [(0, 63), (0, 63), (0, 63), (0, 63)], + [(0, 63), (0, 63), (0, 63), (0, 63)], + [(-9, 83), (-9, 83), (-9, 83), (-9, 83)], + [(4, 86), (4, 86), (4, 86), (4, 86)], + [(0, 97), (0, 97), (0, 97), (0, 97)], + [(-7, 72), (-7, 72), (-7, 72), (-7, 72)], + [(13, 41), (13, 41), (13, 41), (13, 41)], + [(3, 62), (3, 62), (3, 62), (3, 62)], + [(0, 11), (0, 45), (13, 15), (7, 34)], + [(1, 55), (-4, 78), (7, 51), (-9, 88)], + [(0, 69), (-3, 96), (2, 80), (-20, 127)], + [(-17, 127), (-27, 126), (-39, 127), (-36, 127)], + [(-13, 102), (-28, 98), (-18, 91), (-17, 91)], + [(0, 82), (-25, 101), (-17, 96), (-14, 95)], + [(-7, 74), (-23, 67), (-26, 81), (-25, 84)], + [(-21, 107), (-28, 82), (-35, 98), (-25, 86)], + [(-27, 127), (-20, 94), (-24, 102), (-12, 89)], + [(-31, 127), (-16, 83), (-23, 97), (-17, 91)], + [(-24, 127), (-22, 110), (-27, 119), (-31, 127)], + [(-18, 95), (-21, 91), (-24, 99), (-14, 76)], + [(-27, 127), (-18, 102), (-21, 110), (-18, 103)], + [(-21, 114), (-13, 93), (-18, 102), (-13, 90)], + [(-30, 127), (-29, 127), (-36, 127), (-37, 127)], + [(-17, 123), (-7, 92), (0, 80), (11, 80)], + [(-12, 115), (-5, 89), (-5, 89), (5, 76)], + [(-16, 122), (-7, 96), (-7, 94), (2, 84)], + [(-11, 115), (-13, 108), (-4, 92), (5, 78)], + [(-12, 63), (-3, 46), (0, 39), (-6, 55)], + [(-2, 68), (-1, 65), (0, 65), (4, 61)], + [(-15, 84), (-1, 57), (-15, 84), (-14, 83)], + [(-13, 104), (-9, 93), (-35, 127), (-37, 127)], + [(-3, 70), (-3, 74), (-2, 73), (-5, 79)], + [(-8, 93), (-9, 92), (-12, 104), (-11, 104)], + [(-10, 90), (-8, 87), (-9, 91), (-11, 91)], + [(-30, 127), (-23, 126), (-31, 127), (-30, 127)], + [(-1, 74), (5, 54), (3, 55), (0, 65)], + [(-6, 97), (6, 60), (7, 56), (-2, 79)], + [(-7, 91), (6, 59), (7, 55), (0, 72)], + [(-20, 127), (6, 69), (8, 61), (-4, 92)], + [(-4, 56), (-1, 48), (-3, 53), (-6, 56)], + [(-5, 82), (0, 68), (0, 68), (3, 68)], + [(-7, 76), (-4, 69), (-7, 74), (-8, 71)], + [(-22, 125), (-8, 88), (-9, 88), (-13, 98)], + [(-7, 93), (-2, 85), (-13, 103), (-4, 86)], + [(-11, 87), (-6, 78), (-13, 91), (-12, 88)], + [(-3, 77), (-1, 75), (-9, 89), (-5, 82)], + [(-5, 71), (-7, 77), (-14, 92), (-3, 72)], + [(-4, 63), (2, 54), (-8, 76), (-4, 67)], + [(-4, 68), (5, 50), (-12, 87), (-8, 72)], + [(-12, 84), (-3, 68), (-23, 110), (-16, 89)], + [(-7, 62), (1, 50), (-24, 105), (-9, 69)], + [(-7, 65), (6, 42), (-10, 78), (-1, 59)], + [(8, 61), (-4, 81), (-20, 112), (5, 66)], + [(5, 56), (1, 63), (-17, 99), (4, 57)], + [(-2, 66), (-4, 70), (-78, 127), (-4, 71)], + [(1, 64), (0, 67), (-70, 127), (-2, 71)], + [(0, 61), (2, 57), (-50, 127), (2, 58)], + [(-2, 78), (-2, 76), (-46, 127), (-1, 74)], + [(1, 50), (11, 35), (-4, 66), (-4, 44)], + [(7, 52), (4, 64), (-5, 78), (-1, 69)], + [(10, 35), (1, 61), (-4, 71), (0, 62)], + [(0, 44), (11, 35), (-8, 72), (-7, 51)], + [(11, 38), (18, 25), (2, 59), (-4, 47)], + [(1, 45), (12, 24), (-1, 55), (-6, 42)], + [(0, 46), (13, 29), (-7, 70), (-3, 41)], + [(5, 44), (13, 36), (-6, 75), (-6, 53)], + [(31, 17), (-10, 93), (-8, 89), (8, 76)], + [(1, 51), (-7, 73), (-34, 119), (-9, 78)], + [(7, 50), (-2, 73), (-3, 75), (-11, 83)], + [(28, 19), (13, 46), (32, 20), (9, 52)], + [(16, 33), (9, 49), (30, 22), (0, 67)], + [(14, 62), (-7, 100), (-44, 127), (-5, 90)], + [(-13, 108), (9, 53), (0, 54), (1, 67)], + [(-15, 100), (2, 53), (-5, 61), (-15, 72)], + [(-13, 101), (5, 53), (0, 58), (-5, 75)], + [(-13, 91), (-2, 61), (-1, 60), (-8, 80)], + [(-12, 94), (0, 56), (-3, 61), (-21, 83)], + [(-10, 88), (0, 56), (-8, 67), (-21, 64)], + [(-16, 84), (-13, 63), (-25, 84), (-13, 31)], + [(-10, 86), (-5, 60), (-14, 74), (-25, 64)], + [(-7, 83), (-1, 62), (-5, 65), (-29, 94)], + [(-13, 87), (4, 57), (5, 52), (9, 75)], + [(-19, 94), (-6, 69), (2, 57), (17, 63)], + [(1, 70), (4, 57), (0, 61), (-8, 74)], + [(0, 72), (14, 39), (-9, 69), (-5, 35)], + [(-5, 74), (4, 51), (-11, 70), (-2, 27)], + [(18, 59), (13, 68), (18, 55), (13, 91)], + [(-8, 102), (3, 64), (-4, 71), (3, 65)], + [(-15, 100), (1, 61), (0, 58), (-7, 69)], + [(0, 95), (9, 63), (7, 61), (8, 77)], + [(-4, 75), (7, 50), (9, 41), (-10, 66)], + [(2, 72), (16, 39), (18, 25), (3, 62)], + [(-11, 75), (5, 44), (9, 32), (-3, 68)], + [(-3, 71), (4, 52), (5, 43), (-20, 81)], + [(15, 46), (11, 48), (9, 47), (0, 30)], + [(-13, 69), (-5, 60), (0, 44), (1, 7)], + [(0, 62), (-1, 59), (0, 51), (-3, 23)], + [(0, 65), (0, 59), (2, 46), (-21, 74)], + [(21, 37), (22, 33), (19, 38), (16, 66)], + [(-15, 72), (5, 44), (-4, 66), (-23, 124)], + [(9, 57), (14, 43), (15, 38), (17, 37)], + [(16, 54), (-1, 78), (12, 42), (44, -18)], + [(0, 62), (0, 60), (9, 34), (50, -34)], + [(12, 72), (9, 69), (0, 89), (-22, 127)], + [(24, 0), (11, 28), (4, 45), (4, 39)], + [(15, 9), (2, 40), (10, 28), (0, 42)], + [(8, 25), (3, 44), (10, 31), (7, 34)], + [(13, 18), (0, 49), (33, -11), (11, 29)], + [(15, 9), (0, 46), (52, -43), (8, 31)], + [(13, 19), (2, 44), (18, 15), (6, 37)], + [(10, 37), (2, 51), (28, 0), (7, 42)], + [(12, 18), (0, 47), (35, -22), (3, 40)], + [(6, 29), (4, 39), (38, -25), (8, 33)], + [(20, 33), (2, 62), (34, 0), (13, 43)], + [(15, 30), (6, 46), (39, -18), (13, 36)], + [(4, 45), (0, 54), (32, -12), (4, 47)], + [(1, 58), (3, 54), (102, -94), (3, 55)], + [(0, 62), (2, 58), (0, 0), (2, 58)], + [(7, 61), (4, 63), (56, -15), (6, 60)], + [(12, 38), (6, 51), (33, -4), (8, 44)], + [(11, 45), (6, 57), (29, 10), (11, 44)], + [(15, 39), (7, 53), (37, -5), (14, 42)], + [(11, 42), (6, 52), (51, -29), (7, 48)], + [(13, 44), (6, 55), (39, -9), (4, 56)], + [(16, 45), (11, 45), (52, -34), (4, 52)], + [(12, 41), (14, 36), (69, -58), (13, 37)], + [(10, 49), (8, 53), (67, -63), (9, 49)], + [(30, 34), (-1, 82), (44, -5), (19, 58)], + [(18, 42), (7, 55), (32, 7), (10, 48)], + [(10, 55), (-3, 78), (55, -29), (12, 45)], + [(17, 51), (15, 46), (32, 1), (0, 69)], + [(17, 46), (22, 31), (0, 0), (20, 33)], + [(0, 89), (-1, 84), (27, 36), (8, 63)], + [(26, -19), (25, 7), (33, -25), (35, -18)], + [(22, -17), (30, -7), (34, -30), (33, -25)], + [(26, -17), (28, 3), (36, -28), (28, -3)], + [(30, -25), (28, 4), (38, -28), (24, 10)], + [(28, -20), (32, 0), (38, -27), (27, 0)], + [(33, -23), (34, -1), (34, -18), (34, -14)], + [(37, -27), (30, 6), (35, -16), (52, -44)], + [(33, -23), (30, 6), (34, -14), (39, -24)], + [(40, -28), (32, 9), (32, -8), (19, 17)], + [(38, -17), (31, 19), (37, -6), (31, 25)], + [(33, -11), (26, 27), (35, 0), (36, 29)], + [(40, -15), (26, 30), (30, 10), (24, 33)], + [(41, -6), (37, 20), (28, 18), (34, 15)], + [(38, 1), (28, 34), (26, 25), (30, 20)], + [(41, 17), (17, 70), (29, 41), (22, 73)], + [(30, -6), (1, 67), (0, 75), (20, 34)], + [(27, 3), (5, 59), (2, 72), (19, 31)], + [(26, 22), (9, 67), (8, 77), (27, 44)], + [(37, -16), (16, 30), (14, 35), (19, 16)], + [(35, -4), (18, 32), (18, 31), (15, 36)], + [(38, -8), (18, 35), (17, 35), (15, 36)], + [(38, -3), (22, 29), (21, 30), (21, 28)], + [(37, 3), (24, 31), (17, 45), (25, 21)], + [(38, 5), (23, 38), (20, 42), (30, 20)], + [(42, 0), (18, 43), (18, 45), (31, 12)], + [(35, 16), (20, 41), (27, 26), (27, 16)], + [(39, 22), (11, 63), (16, 54), (24, 42)], + [(14, 48), (9, 59), (7, 66), (0, 93)], + [(27, 37), (9, 64), (16, 56), (14, 56)], + [(21, 60), (-1, 94), (11, 73), (15, 57)], + [(12, 68), (-2, 89), (10, 67), (26, 38)], + [(2, 97), (-9, 108), (-10, 116), (-24, 127)], + [(-3, 71), (-6, 76), (-23, 112), (-24, 115)], + [(-6, 42), (-2, 44), (-15, 71), (-22, 82)], + [(-5, 50), (0, 45), (-7, 61), (-9, 62)], + [(-3, 54), (0, 52), (0, 53), (0, 53)], + [(-2, 62), (-3, 64), (-5, 66), (0, 59)], + [(0, 58), (-2, 59), (-11, 77), (-14, 85)], + [(1, 63), (-4, 70), (-9, 80), (-13, 89)], + [(-2, 72), (-4, 75), (-9, 84), (-13, 94)], + [(-1, 74), (-8, 82), (-10, 87), (-11, 92)], + [(-9, 91), (-17, 102), (-34, 127), (-29, 127)], + [(-5, 67), (-9, 77), (-21, 101), (-21, 100)], + [(-5, 27), (3, 24), (-3, 39), (-14, 57)], + [(-3, 39), (0, 42), (-5, 53), (-12, 67)], + [(-2, 44), (0, 48), (-7, 61), (-11, 71)], + [(0, 46), (0, 55), (-11, 75), (-10, 77)], + [(-16, 64), (-6, 59), (-15, 77), (-21, 85)], + [(-8, 68), (-7, 71), (-17, 91), (-16, 88)], + [(-10, 78), (-12, 83), (-25, 107), (-23, 104)], + [(-6, 77), (-11, 87), (-25, 111), (-15, 98)], + [(-10, 86), (-30, 119), (-28, 122), (-37, 127)], + [(-12, 92), (1, 58), (-11, 76), (-10, 82)], + [(-15, 55), (-3, 29), (-10, 44), (-8, 48)], + [(-10, 60), (-1, 36), (-10, 52), (-8, 61)], + [(-6, 62), (1, 38), (-10, 57), (-8, 66)], + [(-4, 65), (2, 43), (-9, 58), (-7, 70)], + [(-12, 73), (-6, 55), (-16, 72), (-14, 75)], + [(-8, 76), (0, 58), (-7, 69), (-10, 79)], + [(-7, 80), (0, 64), (-4, 69), (-9, 83)], + [(-9, 88), (-3, 74), (-5, 74), (-12, 92)], + [(-17, 110), (-10, 90), (-9, 86), (-18, 108)], + [(-11, 97), (0, 70), (2, 66), (-4, 79)], + [(-20, 84), (-4, 29), (-9, 34), (-22, 69)], + [(-11, 79), (5, 31), (1, 32), (-16, 75)], + [(-6, 73), (7, 42), (11, 31), (-2, 58)], + [(-4, 74), (1, 59), (5, 52), (1, 58)], + [(-13, 86), (-2, 58), (-2, 55), (-13, 78)], + [(-13, 96), (-3, 72), (-2, 67), (-9, 83)], + [(-11, 97), (-3, 81), (0, 73), (-4, 81)], + [(-19, 117), (-11, 97), (-8, 89), (-13, 99)], + [(-8, 78), (0, 58), (3, 52), (-13, 81)], + [(-5, 33), (8, 5), (7, 4), (-6, 38)], + [(-4, 48), (10, 14), (10, 8), (-13, 62)], + [(-2, 53), (14, 18), (17, 8), (-6, 58)], + [(-3, 62), (13, 27), (16, 19), (-2, 59)], + [(-13, 71), (2, 40), (3, 37), (-16, 73)], + [(-10, 79), (0, 58), (-1, 61), (-10, 76)], + [(-12, 86), (-3, 70), (-5, 73), (-13, 86)], + [(-13, 90), (-6, 79), (-1, 70), (-9, 83)], + [(-14, 97), (-8, 85), (-4, 78), (-10, 87)], + [(0, 0), (0, 0), (0, 0), (0, 0)], + [(-6, 93), (-13, 106), (-21, 126), (-22, 127)], + [(-6, 84), (-16, 106), (-23, 124), (-25, 127)], + [(-8, 79), (-10, 87), (-20, 110), (-25, 120)], + [(0, 66), (-21, 114), (-26, 126), (-27, 127)], + [(-1, 71), (-18, 110), (-25, 124), (-19, 114)], + [(0, 62), (-14, 98), (-17, 105), (-23, 117)], + [(-2, 60), (-22, 110), (-27, 121), (-25, 118)], + [(-2, 59), (-21, 106), (-27, 117), (-26, 117)], + [(-5, 75), (-18, 103), (-17, 102), (-24, 113)], + [(-3, 62), (-21, 107), (-26, 117), (-28, 118)], + [(-4, 58), (-23, 108), (-27, 116), (-31, 120)], + [(-9, 66), (-26, 112), (-33, 122), (-37, 124)], + [(-1, 79), (-10, 96), (-10, 95), (-10, 94)], + [(0, 71), (-12, 95), (-14, 100), (-15, 102)], + [(3, 68), (-5, 91), (-8, 95), (-10, 99)], + [(10, 44), (-9, 93), (-17, 111), (-13, 106)], + [(-7, 62), (-22, 94), (-28, 114), (-50, 127)], + [(15, 36), (-5, 86), (-6, 89), (-5, 92)], + [(14, 40), (9, 67), (-2, 80), (17, 57)], + [(16, 27), (-4, 80), (-4, 82), (-5, 86)], + [(12, 29), (-10, 85), (-9, 85), (-13, 94)], + [(1, 44), (-1, 70), (-8, 81), (-12, 91)], + [(20, 36), (7, 60), (-1, 72), (-2, 77)], + [(18, 32), (9, 58), (5, 64), (0, 71)], + [(5, 42), (5, 61), (1, 67), (-1, 73)], + [(1, 48), (12, 50), (9, 56), (4, 64)], + [(10, 62), (15, 50), (0, 69), (-7, 81)], + [(17, 46), (18, 49), (1, 69), (5, 64)], + [(9, 64), (17, 54), (7, 69), (15, 57)], + [(-12, 104), (10, 41), (-7, 69), (1, 67)], + [(-11, 97), (7, 46), (-6, 67), (0, 68)], + [(-16, 96), (-1, 51), (-16, 77), (-10, 67)], + [(-7, 88), (7, 49), (-2, 64), (1, 68)], + [(-8, 85), (8, 52), (2, 61), (0, 77)], + [(-7, 85), (9, 41), (-6, 67), (2, 64)], + [(-9, 85), (6, 47), (-3, 64), (0, 68)], + [(-13, 88), (2, 55), (2, 57), (-5, 78)], + [(4, 66), (13, 41), (-3, 65), (7, 55)], + [(-3, 77), (10, 44), (-3, 66), (5, 59)], + [(-3, 76), (6, 50), (0, 62), (2, 65)], + [(-6, 76), (5, 53), (9, 51), (14, 54)], + [(10, 58), (13, 49), (-1, 66), (15, 44)], + [(-1, 76), (4, 63), (-2, 71), (5, 60)], + [(-1, 83), (6, 64), (-2, 75), (2, 70)], + [(-7, 99), (-2, 69), (-1, 70), (-2, 76)], + [(-14, 95), (-2, 59), (-9, 72), (-18, 86)], + [(2, 95), (6, 70), (14, 60), (12, 70)], + [(0, 76), (10, 44), (16, 37), (5, 64)], + [(-5, 74), (9, 31), (0, 47), (-12, 70)], + [(0, 70), (12, 43), (18, 35), (11, 55)], + [(-11, 75), (3, 53), (11, 37), (5, 56)], + [(1, 68), (14, 34), (12, 41), (0, 69)], + [(0, 65), (10, 38), (10, 41), (2, 65)], + [(-14, 73), (-3, 52), (2, 48), (-6, 74)], + [(3, 62), (13, 40), (12, 41), (5, 54)], + [(4, 62), (17, 32), (13, 41), (7, 54)], + [(-1, 68), (7, 44), (0, 59), (-6, 76)], + [(-13, 75), (7, 38), (3, 50), (-11, 82)], + [(11, 55), (13, 50), (19, 40), (-2, 77)], + [(5, 64), (10, 57), (3, 66), (-2, 77)], + [(12, 70), (26, 43), (18, 50), (25, 42)], + [(15, 6), (14, 11), (19, -6), (17, -13)], + [(6, 19), (11, 14), (18, -6), (16, -9)], + [(7, 16), (9, 11), (14, 0), (17, -12)], + [(12, 14), (18, 11), (26, -12), (27, -21)], + [(18, 13), (21, 9), (31, -16), (37, -30)], + [(13, 11), (23, -2), (33, -25), (41, -40)], + [(13, 15), (32, -15), (33, -22), (42, -41)], + [(15, 16), (32, -15), (37, -28), (48, -47)], + [(12, 23), (34, -21), (39, -30), (39, -32)], + [(13, 23), (39, -23), (42, -30), (46, -40)], + [(15, 20), (42, -33), (47, -42), (52, -51)], + [(14, 26), (41, -31), (45, -36), (46, -41)], + [(14, 44), (46, -28), (49, -34), (52, -39)], + [(17, 40), (38, -12), (41, -17), (43, -19)], + [(17, 47), (21, 29), (32, 9), (32, 11)], + [(24, 17), (45, -24), (69, -71), (61, -55)], + [(21, 21), (53, -45), (63, -63), (56, -46)], + [(25, 22), (48, -26), (66, -64), (62, -50)], + [(31, 27), (65, -43), (77, -74), (81, -67)], + [(22, 29), (43, -19), (54, -39), (45, -20)], + [(19, 35), (39, -10), (52, -35), (35, -2)], + [(14, 50), (30, 9), (41, -10), (28, 15)], + [(10, 57), (18, 26), (36, 0), (34, 1)], + [(7, 63), (20, 27), (40, -1), (39, 1)], + [(-2, 77), (0, 57), (30, 14), (30, 17)], + [(-4, 82), (-14, 82), (28, 26), (20, 38)], + [(-3, 94), (-5, 75), (23, 37), (18, 45)], + [(9, 69), (-19, 97), (12, 55), (15, 54)], + [(-12, 109), (-35, 125), (11, 65), (0, 79)], + [(36, -35), (27, 0), (37, -33), (36, -16)], + [(36, -34), (28, 0), (39, -36), (37, -14)], + [(32, -26), (31, -4), (40, -37), (37, -17)], + [(37, -30), (27, 6), (38, -30), (32, 1)], + [(44, -32), (34, 8), (46, -33), (34, 15)], + [(34, -18), (30, 10), (42, -30), (29, 15)], + [(34, -15), (24, 22), (40, -24), (24, 25)], + [(40, -15), (33, 19), (49, -29), (34, 22)], + [(33, -7), (22, 32), (38, -12), (31, 16)], + [(35, -5), (26, 31), (40, -10), (35, 18)], + [(33, 0), (21, 41), (38, -3), (31, 28)], + [(38, 2), (26, 44), (46, -5), (33, 41)], + [(33, 13), (23, 47), (31, 20), (36, 28)], + [(23, 35), (16, 65), (29, 30), (27, 47)], + [(13, 58), (14, 71), (25, 44), (21, 62)], + [(29, -3), (8, 60), (12, 48), (18, 31)], + [(26, 0), (6, 63), (11, 49), (19, 26)], + [(22, 30), (17, 65), (26, 45), (36, 24)], + [(31, -7), (21, 24), (22, 22), (24, 23)], + [(35, -15), (23, 20), (23, 22), (27, 16)], + [(34, -3), (26, 23), (27, 21), (24, 30)], + [(34, 3), (27, 32), (33, 20), (31, 29)], + [(36, -1), (28, 23), (26, 28), (22, 41)], + [(34, 5), (28, 24), (30, 24), (22, 42)], + [(32, 11), (23, 40), (27, 34), (16, 60)], + [(35, 5), (24, 32), (18, 42), (15, 52)], + [(34, 12), (28, 29), (25, 39), (14, 60)], + [(39, 11), (23, 42), (18, 50), (3, 78)], + [(30, 29), (19, 57), (12, 70), (-16, 123)], + [(34, 26), (22, 53), (21, 54), (21, 53)], + [(29, 39), (22, 61), (14, 71), (22, 56)], + [(19, 66), (11, 86), (11, 83), (25, 61)], + [(31, 21), (12, 40), (25, 32), (21, 33)], + [(31, 31), (11, 51), (21, 49), (19, 50)], + [(25, 50), (14, 59), (21, 54), (17, 61)], + [(-17, 120), (-4, 79), (-5, 85), (-3, 78)], + [(-20, 112), (-7, 71), (-6, 81), (-8, 74)], + [(-18, 114), (-5, 69), (-10, 77), (-9, 72)], + [(-11, 85), (-9, 70), (-7, 81), (-10, 72)], + [(-15, 92), (-8, 66), (-17, 80), (-18, 75)], + [(-14, 89), (-10, 68), (-18, 73), (-12, 71)], + [(-26, 71), (-19, 73), (-4, 74), (-11, 63)], + [(-15, 81), (-12, 69), (-10, 83), (-5, 70)], + [(-14, 80), (-16, 70), (-9, 71), (-17, 75)], + [(0, 68), (-15, 67), (-9, 67), (-14, 72)], + [(-14, 70), (-20, 62), (-1, 61), (-16, 67)], + [(-24, 56), (-19, 70), (-8, 66), (-8, 53)], + [(-23, 68), (-16, 66), (-14, 66), (-14, 59)], + [(-24, 50), (-22, 65), (0, 59), (-9, 52)], + [(-11, 74), (-20, 63), (2, 59), (-11, 68)], + [(23, -13), (9, -2), (17, -10), (9, -2)], + [(26, -13), (26, -9), (32, -13), (30, -10)], + [(40, -15), (33, -9), (42, -9), (31, -4)], + [(49, -14), (39, -7), (49, -5), (33, -1)], + [(44, 3), (41, -2), (53, 0), (33, 7)], + [(45, 6), (45, 3), (64, 3), (31, 12)], + [(44, 34), (49, 9), (68, 10), (37, 23)], + [(33, 54), (45, 27), (66, 27), (31, 38)], + [(19, 82), (36, 59), (47, 57), (20, 64)], + [(-3, 75), (-6, 66), (-5, 71), (-9, 71)], + [(-1, 23), (-7, 35), (0, 24), (-7, 37)], + [(1, 34), (-7, 42), (-1, 36), (-8, 44)], + [(1, 43), (-8, 45), (-2, 42), (-11, 49)], + [(0, 54), (-5, 48), (-2, 52), (-10, 56)], + [(-2, 55), (-12, 56), (-9, 57), (-12, 59)], + [(0, 61), (-6, 60), (-6, 63), (-8, 63)], + [(1, 64), (-5, 62), (-4, 65), (-9, 67)], + [(0, 68), (-8, 66), (-4, 67), (-6, 68)], + [(-9, 92), (-8, 76), (-7, 82), (-10, 79)], + [(-14, 106), (-5, 85), (-3, 81), (-3, 78)], + [(-13, 97), (-6, 81), (-3, 76), (-8, 74)], + [(-15, 90), (-10, 77), (-7, 72), (-9, 72)], + [(-12, 90), (-7, 81), (-6, 78), (-10, 72)], + [(-18, 88), (-17, 80), (-12, 72), (-18, 75)], + [(-10, 73), (-18, 73), (-14, 68), (-12, 71)], + [(-9, 79), (-4, 74), (-3, 70), (-11, 63)], + [(-14, 86), (-10, 83), (-6, 76), (-5, 70)], + [(-10, 73), (-9, 71), (-5, 66), (-17, 75)], + [(-10, 70), (-9, 67), (-5, 62), (-14, 72)], + [(-10, 69), (-1, 61), (0, 57), (-16, 67)], + [(-5, 66), (-8, 66), (-4, 61), (-8, 53)], + [(-9, 64), (-14, 66), (-9, 60), (-14, 59)], + [(-5, 58), (0, 59), (1, 54), (-9, 52)], + [(2, 59), (2, 59), (2, 58), (-11, 68)], + [(21, -10), (21, -13), (17, -10), (9, -2)], + [(24, -11), (33, -14), (32, -13), (30, -10)], + [(28, -8), (39, -7), (42, -9), (31, -4)], + [(28, -1), (46, -2), (49, -5), (33, -1)], + [(29, 3), (51, 2), (53, 0), (33, 7)], + [(29, 9), (60, 6), (64, 3), (31, 12)], + [(35, 20), (61, 17), (68, 10), (37, 23)], + [(29, 36), (55, 34), (66, 27), (31, 38)], + [(14, 67), (42, 62), (47, 57), (20, 64)], +]; + + +// --------------------------------------------------------------------------------- +// ctxBlockCat 5 (luma 8x8) position maps — spec Table 9-43. +// +// Moved here from `rusty_h264-decoder/src/mb16.rs` (rip/R6-1) so the ENCODER can share +// them. The decoder has decoded x264's High-profile 8x8 streams bit-exact with these +// since c1375d1/d137218, so they are validated spec data, not a fresh transcription — +// which is the whole reason the encoder work reuses them rather than re-deriving. +// +// Cat 5 is the odd category in two ways, both of which matter to a writer: +// * ctxIdxInc is NOT the scan position (as it is for the 4x4 cats) — 63 positions +// fold onto 15 contexts for `significant_coeff_flag` and 9 for +// `last_significant_coeff_flag`. +// * it carries NO `coded_block_flag`; presence is inferred from +// CodedBlockPatternLuma. Emitting one desyncs the stream. +// --------------------------------------------------------------------------------- + +/// `significant_coeff_flag` ctxIdxInc for ctxBlockCat 5, frame-coded (spec Table 9-43). +/// Absolute ctxIdx is `402 + SIG8X8[pos]` (encoder) / the decoder's matching base. +pub const SIG8X8: [u8; 64] = [ + 0, 1, 2, 3, 4, 5, 5, 4, 4, 3, 3, 4, 4, 4, 5, 5, // + 4, 4, 4, 4, 3, 3, 6, 7, 7, 7, 8, 9, 10, 9, 8, 7, // + 7, 6, 11, 12, 13, 11, 6, 7, 8, 9, 14, 10, 9, 8, 6, 11, // + 12, 13, 11, 6, 9, 14, 10, 9, 11, 12, 13, 11, 14, 10, 12, 14, +]; + +/// `last_significant_coeff_flag` ctxIdxInc for ctxBlockCat 5 (spec Table 9-43). +/// Absolute ctxIdx is `417 + LAST8X8[pos]`. +pub const LAST8X8: [u8; 64] = [ + 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, // + 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, // + 3, 3, 3, 3, 3, 3, 3, 3, 4, 4, 4, 4, 4, 4, 4, 4, // + 5, 5, 5, 5, 6, 6, 6, 6, 7, 7, 7, 7, 8, 8, 8, 8, +]; + +/// ctxIdxOffset bases for ctxBlockCat 5, spec Table 9-34. Named so the encoder's +/// residual writer cannot silently disagree with the decoder's reader. +pub const CAT5_SIG_BASE: usize = 402; +pub const CAT5_LAST_BASE: usize = 417; +pub const CAT5_LEVEL_BASE: usize = 426; diff --git a/vendor/rusty_h264-common/src/cavlc.rs b/vendor/rusty_h264-common/src/cavlc.rs new file mode 100644 index 0000000..1fbd5f3 --- /dev/null +++ b/vendor/rusty_h264-common/src/cavlc.rs @@ -0,0 +1,821 @@ +//! CAVLC — Context-Adaptive Variable-Length Coding of residual blocks. +//! +//! This is the entropy coder that actually compresses: a 4×4 block of quantized +//! coefficients (in zig-zag scan order) is coded as `coeff_token` (count + +//! trailing ones), trailing-one signs, the remaining levels, `total_zeros`, and +//! per-coefficient `run_before`. The VLC tables below are the exact H.264 tables +//! (matching the reference decoders our output is validated against). +//! +//! [`encode_residual_block`] and [`decode_residual_block`] are an exact inverse +//! pair, parameterized by `nc` (the neighbor-derived context that selects the +//! `coeff_token` table) and `max_coeff` (16 for a full 4×4, 15 for an AC block, +//! 4 for chroma DC). Neighbor `nc` bookkeeping lives in the macroblock layer. + +use crate::{BitReader, BitWriter}; +use crate::bit_reader::OutOfData; + +/// 4×4 zig-zag scan: scan position → raster index. +pub const ZIGZAG_4X4: [usize; 16] = [ + 0, 1, 4, 8, 5, 2, 3, 6, 9, 12, 13, 10, 7, 11, 14, 15, +]; + +/// Zig-zag scan of a raster 4×4 block (full DC+AC), **unrolled** like openh264's +/// `WelsScan4x4DcAc` — constant indices, so no `ZIGZAG_4X4[i]` table read and no +/// per-element bounds check (the looped `block[ZIGZAG_4X4[i]]` form forces one). +#[inline] +pub fn scan_4x4_dcac(d: &[i32; 16]) -> [i32; 16] { + [ + 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], + d[14], d[15], + ] +} + +/// Zig-zag scan of the 15 AC coefficients (skipping DC), unrolled like openh264's +/// `WelsScan4x4Ac` (`= ZIGZAG_4X4[1..]`). +#[inline] +pub fn scan_4x4_ac(d: &[i32; 16]) -> [i32; 15] { + [ + 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], + d[15], + ] +} + +/// Inverse of [`scan_4x4_dcac`] (decoder): scatter scan-order coefficients back to +/// the raster 4×4 block, unrolled (no `ZIGZAG_4X4[i]` table read / bounds check). +#[inline] +pub fn un_scan_4x4_dcac(s: &[i32; 16]) -> [i32; 16] { + let mut d = [0i32; 16]; + d[0] = s[0]; + d[1] = s[1]; + d[4] = s[2]; + d[8] = s[3]; + d[5] = s[4]; + d[2] = s[5]; + d[3] = s[6]; + d[6] = s[7]; + d[9] = s[8]; + d[12] = s[9]; + d[13] = s[10]; + d[10] = s[11]; + d[7] = s[12]; + d[11] = s[13]; + d[14] = s[14]; + d[15] = s[15]; + d +} + +/// Inverse of [`scan_4x4_ac`] (decoder): scatter the 15 AC coefficients into the +/// existing block's raster positions (leaving DC `[0]` untouched). `s[0..15]` used. +#[inline] +pub fn un_scan_4x4_ac_into(s: &[i32], d: &mut [i32; 16]) { + d[1] = s[0]; + d[4] = s[1]; + d[8] = s[2]; + d[5] = s[3]; + d[2] = s[4]; + d[3] = s[5]; + d[6] = s[6]; + d[9] = s[7]; + d[12] = s[8]; + d[13] = s[9]; + d[10] = s[10]; + d[7] = s[11]; + d[11] = s[12]; + d[14] = s[13]; + d[15] = s[14]; +} + +/// `coded_block_pattern` for Intra macroblocks (4:2:0), indexed by `codeNum` +/// (the `me(v)` mapping, spec Table 9-4). Maps code number → CBP value. +#[rustfmt::skip] +const CBP_INTRA: [u8; 48] = [ + 47, 31, 15, 0, 23, 27, 29, 30, 7, 11, 13, 14, 39, 43, 45, 46, + 16, 3, 5, 10, 12, 19, 21, 26, 28, 35, 37, 42, 44, 1, 2, 4, + 8, 17, 18, 20, 24, 6, 9, 22, 25, 32, 33, 34, 36, 40, 38, 41, +]; + +/// `coded_block_pattern` for Inter macroblocks (4:2:0), indexed by `codeNum`. +#[rustfmt::skip] +const CBP_INTER: [u8; 48] = [ + 0, 16, 1, 2, 4, 8, 32, 3, 5, 10, 12, 15, 47, 7, 11, 13, + 14, 6, 9, 31, 35, 37, 42, 44, 33, 34, 36, 40, 39, 43, 45, 46, + 17, 18, 20, 24, 19, 21, 26, 28, 23, 27, 29, 30, 22, 25, 38, 41, +]; + +/// Inverse of a `codeNum → cbp` table: `cbp → codeNum`, for a direct lookup in +/// the encoder instead of a 48-entry linear `.position()` scan per macroblock. +const fn invert_cbp(table: &[u8; 48]) -> [u8; 48] { + let mut inv = [0u8; 48]; + let mut i = 0; + while i < 48 { + inv[table[i] as usize] = i as u8; + i += 1; + } + inv +} +const INV_CBP_INTRA: [u8; 48] = invert_cbp(&CBP_INTRA); +const INV_CBP_INTER: [u8; 48] = invert_cbp(&CBP_INTER); + +/// Decodes a `coded_block_pattern` (`me(v)`) for an Intra macroblock. +pub fn read_cbp_intra(r: &mut BitReader) -> Result { + let code_num = r.read_ue()? as usize; + Ok(*CBP_INTRA.get(code_num).unwrap_or(&0) as u32) +} + +/// Encodes a `coded_block_pattern` (`me(v)`) for an Intra macroblock. +pub fn write_cbp_intra(w: &mut BitWriter, cbp: u32) { + w.write_ue(INV_CBP_INTRA[cbp as usize] as u32); +} + +/// Decodes a `coded_block_pattern` (`me(v)`) for an Inter macroblock. +pub fn read_cbp_inter(r: &mut BitReader) -> Result { + let code_num = r.read_ue()? as usize; + Ok(*CBP_INTER.get(code_num).unwrap_or(&0) as u32) +} + +/// Encodes a `coded_block_pattern` (`me(v)`) for an Inter macroblock. +pub fn write_cbp_inter(w: &mut BitWriter, cbp: u32) { + w.write_ue(INV_CBP_INTER[cbp as usize] as u32); +} + +// ---- coeff_token, four nC tables. Index = TotalCoeff*4 + TrailingOnes. ---- + +#[rustfmt::skip] +const COEFF_TOKEN_LEN: [[u8; 68]; 4] = [ + [ + 1,0,0,0, + 6,2,0,0, 8,6,3,0, 9,8,7,5, 10,9,8,6, + 11,10,9,7, 13,11,10,8, 13,13,11,9, 13,13,13,10, + 14,14,13,11, 14,14,14,13, 15,15,14,14, 15,15,15,14, + 16,15,15,15, 16,16,16,15, 16,16,16,16, 16,16,16,16, + ], + [ + 2,0,0,0, + 6,2,0,0, 6,5,3,0, 7,6,6,4, 8,6,6,4, + 8,7,7,5, 9,8,8,6, 11,9,9,6, 11,11,11,7, + 12,11,11,9, 12,12,12,11, 12,12,12,11, 13,13,13,12, + 13,13,13,13, 13,14,13,13, 14,14,14,13, 14,14,14,14, + ], + [ + 4,0,0,0, + 6,4,0,0, 6,5,4,0, 6,5,5,4, 7,5,5,4, + 7,5,5,4, 7,6,6,4, 7,6,6,4, 8,7,7,5, + 8,8,7,6, 9,8,8,7, 9,9,8,8, 9,9,9,8, + 10,9,9,9, 10,10,10,10, 10,10,10,10, 10,10,10,10, + ], + [ + 6,0,0,0, + 6,6,0,0, 6,6,6,0, 6,6,6,6, 6,6,6,6, + 6,6,6,6, 6,6,6,6, 6,6,6,6, 6,6,6,6, + 6,6,6,6, 6,6,6,6, 6,6,6,6, 6,6,6,6, + 6,6,6,6, 6,6,6,6, 6,6,6,6, 6,6,6,6, + ], +]; + +#[rustfmt::skip] +const COEFF_TOKEN_BITS: [[u8; 68]; 4] = [ + [ + 1,0,0,0, + 5,1,0,0, 7,4,1,0, 7,6,5,3, 7,6,5,3, + 7,6,5,4, 15,6,5,4, 11,14,5,4, 8,10,13,4, + 15,14,9,4, 11,10,13,12, 15,14,9,12, 11,10,13,8, + 15,1,9,12, 11,14,13,8, 7,10,9,12, 4,6,5,8, + ], + [ + 3,0,0,0, + 11,2,0,0, 7,7,3,0, 7,10,9,5, 7,6,5,4, + 4,6,5,6, 7,6,5,8, 15,6,5,4, 11,14,13,4, + 15,10,9,4, 11,14,13,12, 8,10,9,8, 15,14,13,12, + 11,10,9,12, 7,11,6,8, 9,8,10,1, 7,6,5,4, + ], + [ + 15,0,0,0, + 15,14,0,0, 11,15,13,0, 8,12,14,12, 15,10,11,11, + 11,8,9,10, 9,14,13,9, 8,10,9,8, 15,14,13,13, + 11,14,10,12, 15,10,13,12, 11,14,9,12, 8,10,13,8, + 13,7,9,12, 9,12,11,10, 5,8,7,6, 1,4,3,2, + ], + [ + 3,0,0,0, + 0,1,0,0, 4,5,6,0, 8,9,10,11, 12,13,14,15, + 16,17,18,19, 20,21,22,23, 24,25,26,27, 28,29,30,31, + 32,33,34,35, 36,37,38,39, 40,41,42,43, 44,45,46,47, + 48,49,50,51, 52,53,54,55, 56,57,58,59, 60,61,62,63, + ], +]; + +/// chroma DC (2×2) coeff_token, index = TotalCoeff*4 + TrailingOnes. +#[rustfmt::skip] +const CHROMA_DC_COEFF_TOKEN_LEN: [u8; 20] = [ + 2,0,0,0, 6,1,0,0, 6,6,3,0, 6,7,7,6, 6,8,8,7, +]; +#[rustfmt::skip] +const CHROMA_DC_COEFF_TOKEN_BITS: [u8; 20] = [ + 1,0,0,0, 7,1,0,0, 4,6,1,0, 3,3,2,5, 2,3,2,0, +]; + +/// total_zeros, indexed `[TotalCoeff-1][total_zeros]` (TotalCoeff 1..15). +#[rustfmt::skip] +const TOTAL_ZEROS_LEN: [[u8; 16]; 15] = [ + [1,3,3,4,4,5,5,6,6,7,7,8,8,9,9,9], + [3,3,3,3,3,4,4,4,4,5,5,6,6,6,6,0], + [4,3,3,3,4,4,3,3,4,5,5,6,5,6,0,0], + [5,3,4,4,3,3,3,4,3,4,5,5,5,0,0,0], + [4,4,4,3,3,3,3,3,4,5,4,5,0,0,0,0], + [6,5,3,3,3,3,3,3,4,3,6,0,0,0,0,0], + [6,5,3,3,3,2,3,4,3,6,0,0,0,0,0,0], + [6,4,5,3,2,2,3,3,6,0,0,0,0,0,0,0], + [6,6,4,2,2,3,2,5,0,0,0,0,0,0,0,0], + [5,5,3,2,2,2,4,0,0,0,0,0,0,0,0,0], + [4,4,3,3,1,3,0,0,0,0,0,0,0,0,0,0], + [4,4,2,1,3,0,0,0,0,0,0,0,0,0,0,0], + [3,3,1,2,0,0,0,0,0,0,0,0,0,0,0,0], + [2,2,1,0,0,0,0,0,0,0,0,0,0,0,0,0], + [1,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0], +]; +#[rustfmt::skip] +const TOTAL_ZEROS_BITS: [[u8; 16]; 15] = [ + [1,3,2,3,2,3,2,3,2,3,2,3,2,3,2,1], + [7,6,5,4,3,5,4,3,2,3,2,3,2,1,0,0], + [5,7,6,5,4,3,4,3,2,3,2,1,1,0,0,0], + [3,7,5,4,6,5,4,3,3,2,2,1,0,0,0,0], + [5,4,3,7,6,5,4,3,2,1,1,0,0,0,0,0], + [1,1,7,6,5,4,3,2,1,1,0,0,0,0,0,0], + [1,1,5,4,3,3,2,1,1,0,0,0,0,0,0,0], + [1,1,1,3,3,2,2,1,0,0,0,0,0,0,0,0], + [1,0,1,3,2,1,1,1,0,0,0,0,0,0,0,0], + [1,0,1,3,2,1,1,0,0,0,0,0,0,0,0,0], + [0,1,1,2,1,3,0,0,0,0,0,0,0,0,0,0], + [0,1,1,1,1,0,0,0,0,0,0,0,0,0,0,0], + [0,1,1,1,0,0,0,0,0,0,0,0,0,0,0,0], + [0,1,1,0,0,0,0,0,0,0,0,0,0,0,0,0], + [0,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0], +]; + +/// chroma DC total_zeros, indexed `[TotalCoeff-1][total_zeros]` (TotalCoeff 1..3). +#[rustfmt::skip] +const CHROMA_DC_TOTAL_ZEROS_LEN: [[u8; 4]; 3] = [ + [1,2,3,3], + [1,2,2,0], + [1,1,0,0], +]; +#[rustfmt::skip] +const CHROMA_DC_TOTAL_ZEROS_BITS: [[u8; 4]; 3] = [ + [1,1,1,0], + [1,1,0,0], + [1,0,0,0], +]; + +/// run_before, indexed `[min(zerosLeft,7)-1][run_before]`. +#[rustfmt::skip] +const RUN_LEN: [[u8; 15]; 7] = [ + [1,1,0,0,0,0,0,0,0,0,0,0,0,0,0], + [1,2,2,0,0,0,0,0,0,0,0,0,0,0,0], + [2,2,2,2,0,0,0,0,0,0,0,0,0,0,0], + [2,2,2,3,3,0,0,0,0,0,0,0,0,0,0], + [2,2,3,3,3,3,0,0,0,0,0,0,0,0,0], + [2,3,3,3,3,3,3,0,0,0,0,0,0,0,0], + [3,3,3,3,3,3,3,4,5,6,7,8,9,10,11], +]; +#[rustfmt::skip] +const RUN_BITS: [[u8; 15]; 7] = [ + [1,0,0,0,0,0,0,0,0,0,0,0,0,0,0], + [1,1,0,0,0,0,0,0,0,0,0,0,0,0,0], + [3,2,1,0,0,0,0,0,0,0,0,0,0,0,0], + [3,2,1,1,0,0,0,0,0,0,0,0,0,0,0], + [3,2,3,2,1,0,0,0,0,0,0,0,0,0,0], + [3,0,1,3,2,5,4,0,0,0,0,0,0,0,0], + [7,6,5,4,3,2,1,1,1,1,1,1,1,1,1], +]; + +/// Selects the coeff_token VLC table from the context `nc`. `nc == -1` is the +/// chroma-DC table (handled separately by the caller). +fn coeff_token_table(nc: i32) -> usize { + if nc < 2 { + 0 + } else if nc < 4 { + 1 + } else if nc < 8 { + 2 + } else { + 3 + } +} + +/// Writes a `(len, bits)` VLC codeword. +fn put(w: &mut BitWriter, len: u8, bits: u8) { + debug_assert!(len > 0, "writing an undefined VLC entry"); + w.write_bits(bits as u32, len as u32); +} + +/// Reads a VLC by matching accumulated bits against a length/bits table over +/// the given candidate symbol indices. Returns the matched symbol index. +/// A flat VLC lookup table. The H.264 VLC tables are prefix-free, so a single +/// `peek_bits(width)` + index decodes any codeword in O(1) — replacing the old +/// bit-at-a-time scan over every candidate. `entry[peeked]` packs +/// `(symbol << 5) | length`; `length == 0` marks "no codeword" (corrupt input). +struct Vlc { + width: u32, + entry: Vec, +} + +impl Vlc { + /// Builds the lookup from a `(len, code)` table. For each codeword of length + /// `l` and value `v`, every `width`-bit peek whose top `l` bits equal `v` + /// (the contiguous range `[v<<(width-l), (v+1)<<(width-l))`) maps to it. Codes + /// are prefix-free, so the ranges never overlap. + fn build(lens: &[u8], bits: &[u8]) -> Vlc { + let width = lens.iter().copied().max().unwrap_or(0) as u32; + let mut entry = vec![0u16; 1usize << width]; + for (i, (&l, &v)) in lens.iter().zip(bits.iter()).enumerate() { + if l == 0 { + continue; + } + let base = (v as usize) << (width - l as u32); + let span = 1usize << (width - l as u32); + let packed = ((i as u16) << 5) | l as u16; + for e in &mut entry[base..base + span] { + *e = packed; + } + } + Vlc { width, entry } + } + + #[inline] + fn read(&self, r: &mut BitReader) -> Result { + let packed = self.entry[r.peek_bits(self.width) as usize]; + let len = (packed & 0x1F) as u32; + if len == 0 { + return Err(OutOfData); // peeked bits matched no codeword → corrupt + } + r.skip_bits(len)?; + Ok((packed >> 5) as usize) + } +} + +/// The CAVLC VLC lookup tables, built once on first decode (≈240 KB). +struct VlcTables { + coeff_token: [Vlc; 4], + chroma_dc_coeff_token: Vlc, + total_zeros: [Vlc; 15], + chroma_dc_total_zeros: [Vlc; 3], + run_before: [Vlc; 7], +} + +fn vlc_tables() -> &'static VlcTables { + use std::sync::OnceLock; + static T: OnceLock = OnceLock::new(); + T.get_or_init(|| VlcTables { + coeff_token: std::array::from_fn(|t| Vlc::build(&COEFF_TOKEN_LEN[t], &COEFF_TOKEN_BITS[t])), + chroma_dc_coeff_token: Vlc::build(&CHROMA_DC_COEFF_TOKEN_LEN, &CHROMA_DC_COEFF_TOKEN_BITS), + total_zeros: std::array::from_fn(|t| Vlc::build(&TOTAL_ZEROS_LEN[t], &TOTAL_ZEROS_BITS[t])), + chroma_dc_total_zeros: std::array::from_fn(|t| { + Vlc::build(&CHROMA_DC_TOTAL_ZEROS_LEN[t], &CHROMA_DC_TOTAL_ZEROS_BITS[t]) + }), + run_before: std::array::from_fn(|t| Vlc::build(&RUN_LEN[t], &RUN_BITS[t])), + }) +} + +/// Maps a signed level to its base `levelCode` (before the first-level offset). +fn level_to_code(level: i32) -> i32 { + if level > 0 { + (level << 1) - 2 + } else { + (-level << 1) - 1 + } +} + +/// Writes one `level_prefix`/`level_suffix` for `code` at the given suffix +/// length, the exact inverse of [`decode_residual_block`]'s level parsing. +/// +/// For small codes the prefix is the unary part and the suffix is `suffix_length` +/// bits. Above that, `level_prefix` escapes to 15 with a 12-bit suffix; and for +/// codes too large for 12 bits, to the **extended escape** (`level_prefix ≥ 16`, +/// suffix `level_prefix − 3` bits), without which large levels — common at very +/// low QP — would silently truncate. +fn write_level(w: &mut BitWriter, code: i32, suffix_length: u32) { + let code = code as u32; + // Short forms with prefix < 15 — prefix+suffix PACKED into one write (the + // value `(1<> suffix_length; + if prefix < 15 { + let suffix = code & ((1 << suffix_length) - 1); + w.write_bits((1u32 << suffix_length) | suffix, prefix + 1 + suffix_length); + return; + } + } + // Prefix ≥ 15. `rem` is the value beyond the prefix-15 base; the decoder's + // `+15` for the suffix_length-0 case makes both bases (30 and 15< (1u32 << (p - 2)) - 4097 { + p += 1; + } + put_zeros_one(w, p); + w.write_bits(rem - ((1 << (p - 3)) - 4096), p - 3); +} + +/// Writes `n` zero bits followed by a `1` (the unary `level_prefix`). +fn put_zeros_one(w: &mut BitWriter, n: u32) { + // `n` zero bits then a `1` is just the value `1` written in `n + 1` bits — one + // write, not `n + 1`. (The level-prefix unary code, emitted for every coeff.) + if n < 32 { + w.write_bits(1, n + 1); + } else { + w.write_bits(0, n - 31); + w.write_bits(1, 32); + } +} + +/// Reads a `level_prefix` (count of leading zeros before a `1`). +fn read_level_prefix(r: &mut BitReader) -> Result { + // Unary prefix = leading zeros before a 1. Count them in the peek window in + // one CLZ when the codeword (lz+1 bits) fits the 24-bit window. + let window = r.peek_bits(24); + let lz = window.leading_zeros() - 8; + if lz < 24 { + r.skip_bits(lz + 1)?; + return Ok(lz); + } + let mut n = 0; + while !r.read_bit()? { + n += 1; + // A conformant 4×4 coefficient never needs a prefix this long; beyond + // this the level computation (`1 << (prefix-3)`) would overflow, so a + // longer run means corrupt input. + if n > 32 { + return Err(OutOfData); + } + } + Ok(n) +} + +/// Encodes a 4×4 residual block (`coeffs` in zig-zag scan order) as CAVLC and +/// returns `total_coeff` (the non-zero count), which callers reuse as the block's +/// `nnz` — saving a separate counting pass. +/// +/// - `max_coeff`: 16 (full), 15 (AC), or 4 (chroma DC). +/// - `nc`: neighbor context; pass `-1` for chroma DC. +pub fn encode_residual_block(w: &mut BitWriter, coeffs: &[i32], max_coeff: usize, nc: i32) -> usize { + // MEASUREMENT: scope disabled — at 600k+/200k+ calls its own rdtsc pair + // was >50% of the bucket and inflated every enclosing stage. + // let _g = crate::prof::scope(crate::prof::Stage::EncWrite); + debug_assert!(coeffs.len() >= max_coeff); + debug_assert!(max_coeff <= 16); + let chroma_dc = nc == -1; + + // openh264 `CavlcParamCal`: ONE descending pass yields levels[] (high→low), + // run[] (high→low), total_coeff, and total_zeros at once — no positions array, + // no second/third pass. Bit-identical to the per-position derivation. Runs for + // every coded 4×4 block, so the saved passes matter. + let mut levels = [0i32; 16]; + let mut run_val = [0usize; 16]; + let mut total_coeff = 0usize; + let mut total_zeros = 0usize; + let mut idx = max_coeff as isize - 1; + while idx >= 0 && coeffs[idx as usize] == 0 { + idx -= 1; + } + while idx >= 0 { + levels[total_coeff] = coeffs[idx as usize]; + idx -= 1; + let mut count_zero = 0usize; + while idx >= 0 && coeffs[idx as usize] == 0 { + count_zero += 1; + idx -= 1; + } + total_zeros += count_zero; + run_val[total_coeff] = count_zero; + total_coeff += 1; + } + let levels_hi_lo = &levels[..total_coeff]; + + // Trailing ones: leading ±1 entries of the high→low list, capped at 3. + let mut trailing_ones = 0usize; + for &lv in levels_hi_lo { + if lv.abs() == 1 && trailing_ones < 3 { + trailing_ones += 1; + } else { + break; + } + } + + // --- coeff_token + trailing-one signs, PACKED into one write (openh264: + // `n += iTrailingOnes; iValue = (iValue << iTrailingOnes) + uiSign`) --- + let tok_idx = total_coeff * 4 + trailing_ones; + let (ct_len, ct_bits) = if chroma_dc { + (CHROMA_DC_COEFF_TOKEN_LEN[tok_idx], CHROMA_DC_COEFF_TOKEN_BITS[tok_idx]) + } else { + let t = coeff_token_table(nc); + (COEFF_TOKEN_LEN[t][tok_idx], COEFF_TOKEN_BITS[t][tok_idx]) + }; + if total_coeff == 0 { + put(w, ct_len, ct_bits); + return 0; + } + // sign bits for the trailing ones (high→low): 1 = negative. + let mut sign = 0u32; + for &lv in levels_hi_lo.iter().take(trailing_ones) { + sign = (sign << 1) | (lv < 0) as u32; + } + w.write_bits( + ((ct_bits as u32) << trailing_ones) | sign, + ct_len as u32 + trailing_ones as u32, + ); + + // --- remaining levels (high→low) --- + let mut suffix_length = if total_coeff > 10 && trailing_ones < 3 { 1 } else { 0 }; + for (k, &lv) in levels_hi_lo.iter().enumerate().skip(trailing_ones) { + let mut code = level_to_code(lv); + if k == trailing_ones && trailing_ones < 3 { + code -= 2; + } + write_level(w, code, suffix_length); + if suffix_length == 0 { + suffix_length = 1; + } + if lv.abs() > (3 << (suffix_length - 1)) && suffix_length < 6 { + suffix_length += 1; + } + } + + // --- total_zeros (computed in the single pass above) --- + if total_coeff < max_coeff { + if chroma_dc { + let row = &CHROMA_DC_TOTAL_ZEROS_LEN[total_coeff - 1]; + let brow = &CHROMA_DC_TOTAL_ZEROS_BITS[total_coeff - 1]; + put(w, row[total_zeros], brow[total_zeros]); + } else { + put( + w, + TOTAL_ZEROS_LEN[total_coeff - 1][total_zeros], + TOTAL_ZEROS_BITS[total_coeff - 1][total_zeros], + ); + } + } + + // --- run_before (high→low), skipping once no zeros remain --- + // run_val[] (high→low) came from the single pass above. + let mut zeros_left = total_zeros; + for &run in run_val[..total_coeff].iter().take(total_coeff - 1) { + if zeros_left == 0 { + break; + } + let t = zeros_left.min(7) - 1; + put(w, RUN_LEN[t][run], RUN_BITS[t][run]); + zeros_left -= run; + } + total_coeff +} + +/// Decodes a CAVLC residual block into zig-zag-ordered coefficients. The first +/// `max_coeff` entries of the returned fixed array are valid (the rest stay zero); +/// returning `[i32; 16]` avoids a per-block heap allocation in the decode loop. +pub fn decode_residual_block( + r: &mut BitReader, + max_coeff: usize, + nc: i32, +) -> Result<[i32; 16], OutOfData> { + let _g = crate::prof::scope(crate::prof::Stage::Entropy); + let chroma_dc = nc == -1; + let mut out = [0i32; 16]; + + // --- coeff_token --- + let tabs = vlc_tables(); + let _tg = crate::prof::scope(crate::prof::Stage::CavTok); + let (total_coeff, trailing_ones) = if chroma_dc { + let idx = tabs.chroma_dc_coeff_token.read(r)?; + (idx / 4, idx % 4) + } else { + let idx = tabs.coeff_token[coeff_token_table(nc)].read(r)?; + (idx / 4, idx % 4) + }; + if total_coeff == 0 { + return Ok(out); + } + // A block cannot hold more coefficients than it has positions. A corrupt + // coeff_token that claims otherwise would index the total_zeros tables and + // the output array out of bounds — reject it. + if total_coeff > max_coeff { + return Err(OutOfData); + } + + // --- trailing-one signs + remaining levels, high→low (stack, no alloc) --- + drop(_tg); + let _lg = crate::prof::scope(crate::prof::Stage::CavLvl); + let mut levels_hi_lo = [0i32; 16]; + for level in levels_hi_lo.iter_mut().take(trailing_ones) { + *level = if r.read_bit()? { -1 } else { 1 }; + } + let mut suffix_length = if total_coeff > 10 && trailing_ones < 3 { 1 } else { 0 }; + // `k` indexes the level array and gates the first-non-T1-level offset. + #[allow(clippy::needless_range_loop)] + for k in trailing_ones..total_coeff { + let level_prefix = read_level_prefix(r)?; + let level_suffix_size = if level_prefix == 14 && suffix_length == 0 { + 4 + } else if level_prefix >= 15 { + level_prefix - 3 + } else { + suffix_length + }; + let level_suffix = if level_suffix_size > 0 { + r.read_bits(level_suffix_size)? + } else { + 0 + }; + let mut level_code = (level_prefix.min(15) << suffix_length) as i32 + level_suffix as i32; + if level_prefix >= 15 && suffix_length == 0 { + level_code += 15; + } + if level_prefix >= 16 { + level_code += (1 << (level_prefix - 3)) - 4096; + } + if k == trailing_ones && trailing_ones < 3 { + level_code += 2; + } + let level = if level_code % 2 == 0 { + (level_code + 2) >> 1 + } else { + (-level_code - 1) >> 1 + }; + // Residual coefficients are 16-bit (spec §8.5; ffmpeg stores int16). A + // value outside that range is non-conformant and would overflow the + // dequant/inverse-transform multiplies — reject the block. + if !(-32768..=32767).contains(&level) { + return Err(OutOfData); + } + levels_hi_lo[k] = level; + if suffix_length == 0 { + suffix_length = 1; + } + if level.abs() > (3 << (suffix_length - 1)) && suffix_length < 6 { + suffix_length += 1; + } + } + + // --- total_zeros --- + drop(_lg); + let _rg = crate::prof::scope(crate::prof::Stage::CavRun); + let total_zeros = if total_coeff < max_coeff { + if chroma_dc { + tabs.chroma_dc_total_zeros[total_coeff - 1].read(r)? + } else { + tabs.total_zeros[total_coeff - 1].read(r)? + } + } else { + 0 + }; + + // --- run_before (stack, no alloc) --- + let mut run_val = [0usize; 16]; + let mut zeros_left = total_zeros; + for run in run_val.iter_mut().take(total_coeff - 1) { + if zeros_left == 0 { + break; + } + let t = zeros_left.min(7) - 1; + let val = tabs.run_before[t].read(r)?; + *run = val; + // A corrupt run_before may exceed the zeros remaining; reject rather + // than underflow. + zeros_left = zeros_left.checked_sub(val).ok_or(OutOfData)?; + } + if total_coeff >= 1 { + run_val[total_coeff - 1] = zeros_left; + } + + // --- reconstruct scan-order coefficients --- + let mut coeff_num: isize = -1; + for i in (0..total_coeff).rev() { + coeff_num += run_val[i] as isize + 1; + // Defensive: with the guards above this stays in 0..max_coeff, but never + // let an attacker-shaped run drive an out-of-bounds write. + let pos = coeff_num as usize; + if pos >= out.len() { + return Err(OutOfData); + } + out[pos] = levels_hi_lo[i]; + } + Ok(out) +} + +#[cfg(test)] +mod tests { + use super::*; + + fn roundtrip(block: &[i32], max_coeff: usize, nc: i32) { + let mut w = BitWriter::new(); + encode_residual_block(&mut w, block, max_coeff, nc); + w.align_zero(); + let bytes = w.into_bytes(); + let mut r = BitReader::new(&bytes); + let decoded = decode_residual_block(&mut r, max_coeff, nc).expect("decode"); + assert_eq!(&decoded[..max_coeff], &block[..max_coeff], "nc={nc} max={max_coeff}"); + } + + #[test] + fn all_zero_block() { + roundtrip(&[0; 16], 16, 0); + roundtrip(&[0; 16], 15, 0); + roundtrip(&[0; 4], 4, -1); + } + + #[test] + fn single_dc() { + let mut b = [0i32; 16]; + b[0] = 5; + roundtrip(&b, 16, 0); + b[0] = -3; + roundtrip(&b, 16, 0); + } + + #[test] + fn trailing_ones_and_levels() { + // DC=3, then some zeros, then ±1 trailing ones at higher frequency. + let b = [3, 0, 1, -1, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]; + roundtrip(&b, 16, 0); + } + + #[test] + fn many_coeffs_all_contexts() { + let b = [1, -2, 3, -1, 1, 1, -1, 2, -3, 1, -1, 1, 1, -1, 1, -1]; + for nc in [0, 2, 4, 8, 20] { + roundtrip(&b, 16, nc); + } + } + + #[test] + fn chroma_dc_blocks() { + roundtrip(&[2, -1, 0, 1], 4, -1); + roundtrip(&[0, 0, 0, -1], 4, -1); + roundtrip(&[1, 1, 1, 1], 4, -1); + } + + #[test] + fn large_levels_use_escape() { + let b = [200, -150, 47, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]; + roundtrip(&b, 16, 0); + } + + #[test] + fn extreme_levels_use_extended_escape() { + // Levels far beyond the 12-bit suffix range force level_prefix ≥ 16; + // these occur at very low QP and previously truncated. Cover both + // suffix_length==0 (single big DC) and grown-suffix_length (a run of + // large levels) paths, and signs. + roundtrip(&[5000, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], 16, 0); + roundtrip(&[-7000, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], 16, 0); + roundtrip(&[30000, -25000, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], 16, 0); + let big = [9000, -9000, 8000, -8000, 7000, -7000, 6000, -6000, 5000, -5000, 4500, + -4500, 4200, -4200, 4096, -4096]; + roundtrip(&big, 16, 0); + // chroma DC and AC blocks with extreme levels too + roundtrip(&[6000, -6000, 5000, -5000], 4, -1); + } + + #[test] + fn pseudo_random_blocks() { + // Deterministic LCG; exercise many shapes across contexts and sizes. + let mut state = 0x1234_5678u32; + let mut next = || { + state = state.wrapping_mul(1_664_525).wrapping_add(1_013_904_223); + state + }; + for _ in 0..2000 { + let mut b = [0i32; 16]; + let density = (next() % 16) as usize; + for slot in b.iter_mut().take(density) { + // small signed values, biased toward ±1 + let v = (next() % 7) as i32 - 3; + *slot = v; + } + // shuffle into scan positions + for i in (1..16).rev() { + let j = (next() as usize) % (i + 1); + b.swap(i, j); + } + let max_coeff = if next() % 3 == 0 { 15 } else { 16 }; + let nc = [0i32, 2, 4, 8][(next() % 4) as usize]; + roundtrip(&b, max_coeff, nc); + } + } +} diff --git a/vendor/rusty_h264-common/src/deblock.rs b/vendor/rusty_h264-common/src/deblock.rs new file mode 100644 index 0000000..d325235 --- /dev/null +++ b/vendor/rusty_h264-common/src/deblock.rs @@ -0,0 +1,2881 @@ +//! In-loop deblocking filter (spec §8.7), all-intra case. +//! +//! Smooths block-edge discontinuities on the reconstructed frame. Because intra +//! prediction uses *pre*-deblocking samples, this runs as a post-pass over the +//! fully-reconstructed frame: macroblocks in raster order, vertical edges then +//! horizontal, filtered in place. For an all-intra picture the boundary +//! strength is positional — 4 on macroblock edges, 3 on internal 4×4 edges. + +/// `α` threshold indexed by `indexA` (= clipped QP), spec Table 8-16. +#[rustfmt::skip] +const ALPHA: [i32; 52] = [ + 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, + 4,4,5,6,7,8,9,10,12,13,15,17,20,22,25,28, + 32,36,40,45,50,56,63,71,80,90,101,113,127,144,162,182,203,226,255,255, +]; + +/// `β` threshold indexed by `indexB`. +#[rustfmt::skip] +const BETA: [i32; 52] = [ + 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, + 2,2,2,3,3,3,3,4,4,4,6,6,7,7,8,8, + 9,9,10,10,11,11,12,12,13,13,14,14,15,15,16,16,17,17,18,18, +]; + +/// `tc0` indexed by `[indexA][bS-1]` for bS ∈ {1,2,3}. +#[rustfmt::skip] +const TC0: [[i32; 3]; 52] = [ + [0,0,0],[0,0,0],[0,0,0],[0,0,0],[0,0,0],[0,0,0],[0,0,0],[0,0,0], + [0,0,0],[0,0,0],[0,0,0],[0,0,0],[0,0,0],[0,0,0],[0,0,0],[0,0,0], + [0,0,0],[0,0,1],[0,0,1],[0,0,1],[0,0,1],[0,1,1],[0,1,1],[1,1,1], + [1,1,1],[1,1,1],[1,1,1],[1,1,2],[1,1,2],[1,1,2],[1,1,2],[1,2,3], + [1,2,3],[2,2,3],[2,2,4],[2,3,4],[2,3,4],[3,3,5],[3,4,6],[3,4,6], + [4,5,7],[4,5,8],[4,6,9],[5,7,10],[6,8,11],[6,8,13],[7,10,14],[8,11,16], + [9,12,18],[10,13,20],[11,15,23],[13,17,25], +]; + +#[inline] +fn clip1(v: i32) -> u8 { + v.clamp(0, 255) as u8 +} + +#[inline] +fn clip3(lo: i32, hi: i32, v: i32) -> i32 { + v.clamp(lo, hi) +} + +/// One sample line crossing an edge: `p3..p0 | q0..q3` (indices 0..3 from the +/// edge outward). Reads/writes a plane along `stride`-spaced positions. +struct Line { + /// Byte offset of q0 (the first sample on the "right"/"below" side). + base: usize, + /// Step between adjacent samples across the edge (1 horizontally, `stride` + /// vertically). + step: isize, +} + +/// Filters luma samples across one edge line. `bs` is 3 (internal) or 4 (MB edge). +#[allow(clippy::too_many_arguments)] +fn filter_luma_line(plane: &mut [u8], line: &Line, bs: i32, alpha: i32, beta: i32, tc0: i32) { + let at = |i: isize| -> i32 { + plane[(line.base as isize + i * line.step) as usize] as i32 + }; + let (p0, p1, p2, p3) = (at(-1), at(-2), at(-3), at(-4)); + let (q0, q1, q2, q3) = (at(0), at(1), at(2), at(3)); + + if (p0 - q0).abs() >= alpha || (p1 - p0).abs() >= beta || (q1 - q0).abs() >= beta { + return; + } + let set = |plane: &mut [u8], i: isize, v: u8| { + plane[(line.base as isize + i * line.step) as usize] = v; + }; + let ap = (p2 - p0).abs(); + let aq = (q2 - q0).abs(); + + if bs < 4 { + let tc = tc0 + (ap < beta) as i32 + (aq < beta) as i32; + let delta = clip3(-tc, tc, (((q0 - p0) << 2) + (p1 - q1) + 4) >> 3); + set(plane, -1, clip1(p0 + delta)); + set(plane, 0, clip1(q0 - delta)); + if ap < beta { + let d = clip3(-tc0, tc0, (p2 + ((p0 + q0 + 1) >> 1) - (p1 << 1)) >> 1); + set(plane, -2, clip1(p1 + d)); + } + if aq < beta { + let d = clip3(-tc0, tc0, (q2 + ((p0 + q0 + 1) >> 1) - (q1 << 1)) >> 1); + set(plane, 1, clip1(q1 + d)); + } + } else { + let strong = (p0 - q0).abs() < (alpha >> 2) + 2; + if strong && ap < beta { + set(plane, -1, clip1((p2 + 2 * p1 + 2 * p0 + 2 * q0 + q1 + 4) >> 3)); + set(plane, -2, clip1((p2 + p1 + p0 + q0 + 2) >> 2)); + set(plane, -3, clip1((2 * p3 + 3 * p2 + p1 + p0 + q0 + 4) >> 3)); + } else { + set(plane, -1, clip1((2 * p1 + p0 + q1 + 2) >> 2)); + } + if strong && aq < beta { + set(plane, 0, clip1((q2 + 2 * q1 + 2 * q0 + 2 * p0 + p1 + 4) >> 3)); + set(plane, 1, clip1((q2 + q1 + q0 + p0 + 2) >> 2)); + set(plane, 2, clip1((2 * q3 + 3 * q2 + q1 + q0 + p0 + 4) >> 3)); + } else { + set(plane, 0, clip1((2 * q1 + q0 + p1 + 2) >> 2)); + } + } +} + +/// Filters chroma samples across one edge line (only p0/q0 are modified). +fn filter_chroma_line(plane: &mut [u8], line: &Line, bs: i32, alpha: i32, beta: i32, tc0: i32) { + let at = |i: isize| -> i32 { + plane[(line.base as isize + i * line.step) as usize] as i32 + }; + let (p0, p1) = (at(-1), at(-2)); + let (q0, q1) = (at(0), at(1)); + if (p0 - q0).abs() >= alpha || (p1 - p0).abs() >= beta || (q1 - q0).abs() >= beta { + return; + } + let set = |plane: &mut [u8], i: isize, v: u8| { + plane[(line.base as isize + i * line.step) as usize] = v; + }; + if bs < 4 { + let tc = tc0 + 1; + let delta = clip3(-tc, tc, (((q0 - p0) << 2) + (p1 - q1) + 4) >> 3); + set(plane, -1, clip1(p0 + delta)); + set(plane, 0, clip1(q0 - delta)); + } else { + set(plane, -1, clip1((2 * p1 + p0 + q1 + 2) >> 2)); + set(plane, 0, clip1((2 * q1 + q0 + p1 + 2) >> 2)); + } +} + +/// Per-4×4-block macroblock info driving boundary-strength derivation. +pub struct BlockInfo<'a> { + /// `true` if the block is **inter**-coded (an intra block is `!inter`). Taking + /// the caller's existing inter mask avoids allocating an inverted intra mask + /// per frame in both the decoder and encoder. + pub inter: &'a [bool], + /// Non-zero coefficient count of the block. + pub nnz: &'a [u8], + /// List-0 block motion vector (quarter-pel); ignored for intra. + pub mv: &'a [(i32, i32)], + /// List-0 reference *picture identity* (a stable per-picture id — PicOrderCnt + /// for the decoder, ref index for the encoder; `i32::MIN` = unused/intra). + /// Boundary strength compares the *set* of reference pictures, so the same + /// picture used via different lists matches (spec §8.7.2.1). + pub ref_id: &'a [i32], + /// List-1 motion + reference identity for B blocks (`ref_id1 = i32::MIN` + /// everywhere for P/I, so the extra slot is a no-op there). + pub mv1: &'a [(i32, i32)], + pub ref_id1: &'a [i32], + /// Block-grid width (`mb_w * 4`). + pub w4: usize, + /// Per-macroblock `transform_size_8x8_flag` (length `mb_w * mb_h`). When set, + /// the macroblock's internal 4×4 luma edges (sample columns/rows 4 and 12) + /// are *not* transform boundaries and must not be filtered (spec §8.7). + pub t8x8: &'a [bool], + /// Boundary strengths already derived by the caller, one entry per macroblock + /// in raster order. Empty = derive them here (the decoder path). + pub bs: &'a [MbBs], + /// OPTIONAL reference→identity maps (Brick: WHYS Part 15 item 2). When + /// non-empty, `ref_id`/`ref_id1` hold RAW per-block reference INDICES + /// (negative = none) and these ≤16-entry tables map index → picture + /// identity (POC). This lets the decoder pass its `ref_idx` grids directly + /// instead of materializing two frame-wide pre-mapped `Vec` shims + /// (230-460 KB + 57,600 mapped elements per frame). Empty = `ref_id` + /// already carries identities (the encoder path and all older callers). + pub poc0: &'a [i32], + pub poc1: &'a [i32], + /// Per-macroblock derivation CLASS (`MB_KIND_*`), one entry per macroblock in + /// raster order. Empty, or `MB_KIND_UNSET`, means "not classified" and the + /// blind gather+derive runs for that macroblock. + /// + /// SAFETY-BY-DESIGN: an unclassified macroblock costs SPEED, never + /// correctness. That inversion is deliberate — the alternative design, where + /// the producer must hit every macroblock exit point or strengths silently go + /// wrong, is exactly the failure `MbBs::UNSET` exists to guard against. + /// + /// The producer must be CONSERVATIVE. In particular `B_Skip` and + /// `B_Direct_16x16` are NOT `MB_KIND_SKIP`: their motion comes from direct + /// prediction and may differ per 4x4 sub-block, so internal edges can legally + /// reach strength 1. Only classify what is uniform BY SYNTAX. + pub kind: &'a [u8], +} + +/// Not classified — take the blind path. Any value outside `0..=3` behaves this way. +pub const MB_KIND_UNSET: u8 = 255; +pub const MB_KIND_INTRA: u8 = 0; +pub const MB_KIND_SKIP: u8 = 1; +pub const MB_KIND_INTER_UNIFORM: u8 = 2; +pub const MB_KIND_INTER: u8 = 3; + +impl MbKind { + /// Decode a producer-supplied class byte. `None` = derive blindly. + #[inline] + pub fn from_u8(v: u8) -> Option { + match v { + MB_KIND_INTRA => Some(MbKind::Intra), + MB_KIND_SKIP => Some(MbKind::Skip), + MB_KIND_INTER_UNIFORM => Some(MbKind::InterUniform), + MB_KIND_INTER => Some(MbKind::Inter), + _ => None, + } + } +} + +/// One macroblock's boundary strengths: `[edge group][segment]` per direction. +/// +/// 32 bytes, mirroring x264's `uint8_t bs[2][8][4]`. Deriving these during ENCODE +/// lets the deblocking pass skip the neighbourhood gather and the derivation. +#[derive(Clone, Copy, Default, PartialEq, Eq, Debug)] +pub struct MbBs { + /// Vertical edges (block columns 0..4); index 0 is the macroblock edge. + pub v: [[u8; 4]; 4], + /// Horizontal edges (block rows 0..4); index 0 is the macroblock edge. + pub h: [[u8; 4]; 4], +} + +impl MbBs { + /// "Not yet derived". The macroblock loop has several exits (free skip, + /// greedy skip, coded) and every one must store its strengths; missing one + /// leaves zeros, silently disabling deblocking for that macroblock — which is + /// exactly the bug the byte-identical gate caught during bring-up. + pub const UNSET: MbBs = MbBs { v: [[0xFF; 4]; 4], h: [[0xFF; 4]; 4] }; +} + +/// Sentinel for an unused reference slot. +const NO_REF: i32 = i32::MIN; + +/// One 4×4 block's deblocking state, gathered into a per-macroblock tile. +/// +/// The frame-wide `inter`/`nnz`/`mv`/`ref_id` arrays are indexed `by * w4 + bx`, +/// so deriving boundary strengths straight from them costs ~290 scattered loads +/// per macroblock (each block is re-read by up to four edges, and vertical edge +/// groups stride by `w4`). Gathering the 24 blocks an MB can touch into this +/// contiguous tile once turns all 48 edge decisions into stack/L1 reads. x264 +/// gets the same effect from its `scan8` cache, which is what lets its +/// `deblock_strength` kernel be SIMD at ~15 ns/MB. +#[derive(Clone, Copy, Default)] +struct Blk { + inter: bool, + /// `nnz != 0` — the count itself never matters, only whether it is non-zero. + nz: bool, + ref_id: i32, + mvx: i32, + mvy: i32, + /// List-1 slot (B slices). `NO_REF` on P/I tiles and on uni-L0 blocks, which + /// keeps every comparison below on its single-list fast path there. + ref1: i32, + mv1x: i32, + mv1y: i32, +} + +impl Blk { + #[inline] + fn load(info: &BlockInfo, i: usize) -> Self { + #[cfg(feature = "profile")] + census::BLK_LOADS.fetch_add(1, std::sync::atomic::Ordering::Relaxed); + let (mvx, mvy) = info.mv[i]; + let (ref1, (mv1x, mv1y)) = if info.ref_id1.is_empty() { + (NO_REF, (0, 0)) + } else { + (info.rid1(i), info.mv1[i]) + }; + Blk { inter: info.inter[i], nz: info.nnz[i] != 0, ref_id: info.rid(i), mvx, mvy, ref1, mv1x, mv1y } + } + + /// Whether two blocks are identical for flat-inter purposes (both lists — + /// on P tiles the list-1 fields are uniformly `NO_REF`/0, so the extra + /// compares are always-true and the P behaviour is unchanged). + #[inline] + fn same_motion(&self, o: &Blk) -> bool { + self.ref_id == o.ref_id + && self.mvx == o.mvx + && self.mvy == o.mvy + && self.ref1 == o.ref1 + && self.mv1x == o.mv1x + && self.mv1y == o.mv1y + } +} + +/// The bS==1 motion test on tile entries — mirrors [`BlockInfo::inter_bs1`] +/// exactly (its oracle), including the two-slot B rule, but reads registers +/// instead of strided frame arrays. The single-list fast path fires whenever +/// neither side carries a List-1 slot: all of P, and B edges between uni-L0 +/// blocks (equivalent to the general rule at n<=1 — a differing ref covers the +/// differing-slot-count case, two unused slots give false). +#[inline] +fn bs1_tile(p: &Blk, q: &Blk) -> bool { + if (p.ref1 == NO_REF) & (q.ref1 == NO_REF) { + let far = ((p.mvx - q.mvx).abs() >= 4) | ((p.mvy - q.mvy).abs() >= 4); + return (p.ref_id != q.ref_id) | ((p.ref_id != NO_REF) & far); + } + let used = |b: &Blk| { + let mut v = [(0i32, (0i32, 0i32)); 2]; + let mut n = 0usize; + if b.ref_id != NO_REF { + v[n] = (b.ref_id, (b.mvx, b.mvy)); + n += 1; + } + if b.ref1 != NO_REF { + v[n] = (b.ref1, (b.mv1x, b.mv1y)); + n += 1; + } + (v, n) + }; + let (pv, pn) = used(p); + let (qv, qn) = used(q); + if pn != qn { + return true; + } + let far = |a: (i32, i32), b: (i32, i32)| (a.0 - b.0).abs() >= 4 || (a.1 - b.1).abs() >= 4; + match pn { + 0 => false, + 1 => pv[0].0 != qv[0].0 || far(pv[0].1, qv[0].1), + _ => { + let direct = !far(pv[0].1, qv[0].1) && !far(pv[1].1, qv[1].1); + let swap = !far(pv[0].1, qv[1].1) && !far(pv[1].1, qv[0].1); + if pv[0].0 == pv[1].0 { + qv[0].0 != pv[0].0 || qv[1].0 != pv[0].0 || !(direct || swap) + } else if pv[0].0 == qv[0].0 && pv[1].0 == qv[1].0 { + !direct + } else if pv[0].0 == qv[1].0 && pv[1].0 == qv[0].0 { + !swap + } else { + true + } + } + } +} + +/// Boundary strength from tile entries (spec §8.7.2.1). +/// Branchless for the same reason as [`BlockInfo::bs_branchless`], but now with +/// every operand already in a register rather than behind a strided load. +#[inline] +fn bs_tile(p: &Blk, q: &Blk, mb_edge: bool) -> i32 { + let intra = !(p.inter & q.inter); + let nz = p.nz | q.nz; + let moved = bs1_tile(p, q); + let intra_bs = if mb_edge { 4 } else { 3 }; + let non_intra = if nz { 2 } else { moved as i32 }; + if intra { + intra_bs + } else { + non_intra + } +} + +/// Boundary strength for an edge where BOTH sides are inter — the only case left +/// once the per-macroblock intra fills in [`derive_mb_bs`] have run. It can never +/// return 3 or 4, which is precisely why x264's `deblock_strength` kernel is +/// branch-light enough to vectorise: the intra strengths are not its job. +#[inline] +fn bs_inter(p: &Blk, q: &Blk) -> i32 { + let nz = p.nz | q.nz; + let moved = bs1_tile(p, q); + if nz { + 2 + } else { + moved as i32 + } +} + +/// MB-KIND CENSUS — measurement only, `--features profile`, so the shipped and +/// benchmarked binaries carry no counter at all (atomics in a 6.5M-call loop have +/// measured ~15% wall inflation elsewhere in this workspace). +/// +/// Exists to size the prize of a KIND-AWARE derivation arithmetically before one +/// is built. `derive_mb_kind` already reads nothing for Intra, 9 blocks for Skip +/// and 16 nnz bytes for InterUniform, against 24 blocks across 5-7 grids for the +/// blind `derive_mb` the decoder currently calls — but that only pays if the +/// cheap kinds actually dominate real content. Count first. +#[cfg(feature = "profile")] +pub mod census { + use std::sync::atomic::{AtomicU64, Ordering}; + pub static INTRA: AtomicU64 = AtomicU64::new(0); + pub static SKIP: AtomicU64 = AtomicU64::new(0); + pub static UNIFORM: AtomicU64 = AtomicU64::new(0); + pub static INTER: AtomicU64 = AtomicU64::new(0); + /// Block VISITS made by the predicate walk(s). The timing instruments on this + /// box cannot resolve the fusion (two whole-decode runs disagreed in sign; the + /// anatomy bench's within-arm spread reached 45%), so the bankable evidence is + /// the work actually removed, which no amount of drift can move. + pub static PRED_VISITS: AtomicU64 = AtomicU64::new(0); + /// Every `Blk::load` — the per-block, multi-array gather that Brick 2 exists to + /// avoid. This is the PRIMARY evidence for the brick (codec-measurement §15): + /// one run, drift-immune, and it sizes the win as well as proving it. + pub static BLK_LOADS: AtomicU64 = AtomicU64::new(0); + /// Macroblocks that took the PACKED derivation. Coverage matters: a + /// byte-identical result proves nothing if the path never engaged. + pub static PACKED_MB: AtomicU64 = AtomicU64::new(0); + /// Macroblocks that actually REACH the motion-mask derivation (not intra, not + /// uniform) — the denominator for any kernel prize. + pub static MASKS_CALLS: AtomicU64 = AtomicU64::new(0); + /// ...of those, served by the AVX2 single-list kernel (`l1_used == 0`). + pub static MASKS_KERNEL: AtomicU64 = AtomicU64::new(0); + /// ...of those, forced to the scalar two-list set-match (`l1_used != 0`). + /// THIS is the population a two-list kernel would win, and nothing else. + pub static MASKS_L1: AtomicU64 = AtomicU64::new(0); + + pub fn reset() { + for c in [ + &INTRA, &SKIP, &UNIFORM, &INTER, &PRED_VISITS, &BLK_LOADS, &PACKED_MB, + &MASKS_CALLS, &MASKS_KERNEL, &MASKS_L1, + ] { + c.store(0, Ordering::Relaxed); + } + } + + /// Per-kind gather cost in BLOCK LOADS, from `derive_mb_kind`'s own structure. + /// The projection below is a load-count model, not a timing — it says what is + /// worth measuring, and the measurement still has to happen. + pub fn dump() { + let (i, s, u, n) = ( + INTRA.load(Ordering::Relaxed), + SKIP.load(Ordering::Relaxed), + UNIFORM.load(Ordering::Relaxed), + INTER.load(Ordering::Relaxed), + ); + let tot = (i + s + u + n).max(1); + eprintln!("--- MB-kind census (deblock bS derivation) — {tot} macroblocks ---"); + for (name, n_mb, blocks) in + [("Intra", i, 0u64), ("Skip", s, 9), ("InterUniform", u, 16), ("Inter", n, 24)] + { + eprintln!( + " {name:<13} {n_mb:>10} MB {:>5.1}% kind-aware gather: {blocks:>2} blocks vs 24 blind", + 100.0 * n_mb as f64 / tot as f64 + ); + } + eprintln!( + " Blk::load GATHER loads: {} ({:.2} per MB)", + BLK_LOADS.load(Ordering::Relaxed), + BLK_LOADS.load(Ordering::Relaxed) as f64 / tot as f64 + ); + eprintln!( + " predicate-walk block VISITS: {} ({:.2} per MB)", + PRED_VISITS.load(Ordering::Relaxed), + PRED_VISITS.load(Ordering::Relaxed) as f64 / tot as f64 + ); + eprintln!( + " PACKED-path macroblocks: {}", + PACKED_MB.load(Ordering::Relaxed) + ); + let mc = MASKS_CALLS.load(Ordering::Relaxed).max(1); + eprintln!( + " mask derivations: {} (AVX2 kernel {} = {:.1}%, scalar two-list {} = {:.1}%)", + MASKS_CALLS.load(Ordering::Relaxed), + MASKS_KERNEL.load(Ordering::Relaxed), + 100.0 * MASKS_KERNEL.load(Ordering::Relaxed) as f64 / mc as f64, + MASKS_L1.load(Ordering::Relaxed), + 100.0 * MASKS_L1.load(Ordering::Relaxed) as f64 / mc as f64, + ); + let blind = 24.0 * tot as f64; + let aware = (0 * i + 9 * s + 16 * u + 24 * n) as f64; + eprintln!( + " => block loads {:.0} -> {:.0} ({:.1}% of the gather removed)", + blind, + aware, + 100.0 * (1.0 - aware / blind) + ); + } +} + +/// Derive one macroblock's 32 boundary strengths (2 directions × 4 edge groups × +/// 4 segments), x264-style. +/// +/// The structural point: `mb_type` is a per-MACROBLOCK syntax element, so a +/// macroblock is wholly intra or wholly inter and intra-ness is not a per-edge +/// property. That turns the two expensive cases into constant fills — +/// * intra macroblock → internal edges are the constant 3, its own macroblock +/// edges the constant 4; +/// * flat inter (skip) macroblock → every internal strength is 0; +/// — and leaves [`bs_inter`] for the rest. Pinned by `derive_matches_per_edge`. +#[inline] +fn derive_mb_bs( + tile: &Tile, + mb_x: usize, + mb_y: usize, + flat_inter: bool, + uniform_motion: bool, + mb_t8: bool, + bs_v: &mut [[i32; 4]; 4], + bs_h: &mut [[i32; 4]; 4], +) { + let cur_intra = !tile[1][1].inter; + + #[cfg(feature = "profile")] + { + use std::sync::atomic::Ordering::Relaxed; + let c = if cur_intra { + &census::INTRA + } else if flat_inter { + &census::SKIP + } else if uniform_motion { + &census::UNIFORM + } else { + &census::INTER + }; + c.fetch_add(1, Relaxed); + } + + // ---- macroblock edges: 4 if EITHER side is intra, else an inter compare ---- + if mb_x > 0 { + bs_v[0] = if cur_intra || !tile[1][0].inter { + [4; 4] + } else { + std::array::from_fn(|seg| bs_inter(&tile[seg + 1][0], &tile[seg + 1][1])) + }; + } + if mb_y > 0 { + bs_h[0] = if cur_intra || !tile[0][1].inter { + [4; 4] + } else { + std::array::from_fn(|seg| bs_inter(&tile[0][seg + 1], &tile[1][seg + 1])) + }; + } + + // ---- internal edges ---- + if flat_inter { + return; // all zero by construction (no coefficients, one shared ref+mv) + } + for be in 1..4usize { + // An 8×8-transform macroblock has no transform boundary at 4×4 edges 1/3. + if mb_t8 && (be == 1 || be == 3) { + continue; + } + if cur_intra { + bs_v[be] = [3; 4]; + bs_h[be] = [3; 4]; + } else if uniform_motion { + // Coefficients alone; 0 or 2, no motion compare. + bs_v[be] = std::array::from_fn(|seg| { + 2 * (tile[seg + 1][be].nz | tile[seg + 1][be + 1].nz) as i32 + }); + bs_h[be] = std::array::from_fn(|seg| { + 2 * (tile[be][seg + 1].nz | tile[be + 1][seg + 1].nz) as i32 + }); + } else { + // Both sides are inside this macroblock, so no neighbour read at all. + bs_v[be] = std::array::from_fn(|seg| bs_inter(&tile[seg + 1][be], &tile[seg + 1][be + 1])); + bs_h[be] = std::array::from_fn(|seg| bs_inter(&tile[be][seg + 1], &tile[be + 1][seg + 1])); + } + } +} + +/// What the encoder already knows about a macroblock the moment it finishes +/// coding it. Passing it in turns most macroblocks into constant fills and +/// removes the neighbourhood gather that made deriving in the encode loop cost +/// MORE than deriving in the deblocking pass (the loop's working set is far more +/// contended, so a 24-block gather there evicts live encoder data). +#[derive(Clone, Copy, PartialEq, Eq, Debug)] +pub enum MbKind { + /// Intra: internal strengths are the constant 3, its own macroblock edges 4. + /// Needs NO block reads at all. + Intra, + /// Skip — no coefficients, one shared reference and motion vector — so every + /// internal strength is 0 and only the two macroblock edges are derived. + Skip, + /// Coded inter with a SINGLE partition (P_L0_16x16 — the fast preset's only + /// inter mode). All 16 blocks share one reference and motion vector, so no + /// internal edge can reach strength 1: internal strengths depend on + /// coefficients alone, and the derivation reads 16 nnz bytes instead of + /// gathering 24 blocks across four grids. + InterUniform, + /// Coded inter, multiple partitions: the full derivation. + Inter, +} + +/// Boundary strengths for a macroblock whose kind the caller already knows. +/// +/// `Intra` reads nothing; `Skip` reads one of its own blocks plus the neighbour +/// column/row (9 instead of 24); only `Inter` pays the full gather. +/// `derive_mb_kind_into` writes the deblock loop's `i32` arrays directly. +pub fn derive_mb_kind_into( + info: &BlockInfo, + mb_x: usize, + mb_y: usize, + kind: MbKind, + bs_v: &mut [[i32; 4]; 4], + bs_h: &mut [[i32; 4]; 4], +) { + // Direct i32 writes — no MbBs staging + 32 u8→i32 casts. + *bs_v = [[0; 4]; 4]; + *bs_h = [[0; 4]; 4]; + let (bx0, by0) = (mb_x * 4, mb_y * 4); + let w4 = info.w4; + match kind { + MbKind::Intra => { + if mb_x > 0 { + bs_v[0] = [4; 4]; + } + if mb_y > 0 { + bs_h[0] = [4; 4]; + } + for e in 1..4 { + bs_v[e] = [3; 4]; + bs_h[e] = [3; 4]; + } + } + MbKind::Skip => { + let me = Blk::load(info, by0 * w4 + bx0); + if mb_x > 0 { + bs_v[0] = std::array::from_fn(|seg| { + let p = Blk::load(info, (by0 + seg) * w4 + bx0 - 1); + if p.inter { + bs_inter(&p, &me) + } else { + 4 + } + }); + } + if mb_y > 0 { + bs_h[0] = std::array::from_fn(|seg| { + let p = Blk::load(info, (by0 - 1) * w4 + bx0 + seg); + if p.inter { + bs_inter(&p, &me) + } else { + 4 + } + }); + } + } + MbKind::InterUniform => { + for e in 1..4usize { + bs_v[e] = std::array::from_fn(|seg| { + let i = (by0 + seg) * w4 + bx0 + e; + 2 * ((info.nnz[i] != 0) | (info.nnz[i - 1] != 0)) as i32 + }); + bs_h[e] = std::array::from_fn(|seg| { + let i = (by0 + e) * w4 + bx0 + seg; + 2 * ((info.nnz[i] != 0) | (info.nnz[i - w4] != 0)) as i32 + }); + } + if mb_x > 0 { + bs_v[0] = std::array::from_fn(|seg| { + let qi = (by0 + seg) * w4 + bx0; + let p = Blk::load(info, qi - 1); + if p.inter { + bs_inter(&p, &Blk::load(info, qi)) + } else { + 4 + } + }); + } + if mb_y > 0 { + bs_h[0] = std::array::from_fn(|seg| { + let qi = by0 * w4 + bx0 + seg; + let p = Blk::load(info, qi - w4); + if p.inter { + bs_inter(&p, &Blk::load(info, qi)) + } else { + 4 + } + }); + } + } + MbKind::Inter => { + let m = derive_mb(info, mb_x, mb_y, false); + for e in 0..4 { + for sg in 0..4 { + bs_v[e][sg] = m.v[e][sg] as i32; + bs_h[e][sg] = m.h[e][sg] as i32; + } + } + } + } +} + +pub fn derive_mb_kind(info: &BlockInfo, mb_x: usize, mb_y: usize, kind: MbKind) -> MbBs { + let (bx0, by0) = (mb_x * 4, mb_y * 4); + let w4 = info.w4; + match kind { + MbKind::Intra => { + let mut m = MbBs::default(); + if mb_x > 0 { + m.v[0] = [4; 4]; + } + if mb_y > 0 { + m.h[0] = [4; 4]; + } + for e in 1..4 { + m.v[e] = [3; 4]; + m.h[e] = [3; 4]; + } + m + } + MbKind::Skip => { + // Internal strengths stay 0: no coefficients and one shared (ref, mv) + // means no internal edge can reach strength 1 or 2. + let mut m = MbBs::default(); + let me = Blk::load(info, by0 * w4 + bx0); // all 16 blocks are identical + if mb_x > 0 { + m.v[0] = std::array::from_fn(|seg| { + let p = Blk::load(info, (by0 + seg) * w4 + bx0 - 1); + if p.inter { bs_inter(&p, &me) as u8 } else { 4 } + }); + } + if mb_y > 0 { + m.h[0] = std::array::from_fn(|seg| { + let p = Blk::load(info, (by0 - 1) * w4 + bx0 + seg); + if p.inter { bs_inter(&p, &me) as u8 } else { 4 } + }); + } + m + } + MbKind::InterUniform => { + let mut m = MbBs::default(); + // Internal edges: uniform motion means only coefficients can raise a + // strength, and then only to 2. + for e in 1..4usize { + m.v[e] = std::array::from_fn(|seg| { + let i = (by0 + seg) * w4 + bx0 + e; + 2 * ((info.nnz[i] != 0) | (info.nnz[i - 1] != 0)) as u8 + }); + m.h[e] = std::array::from_fn(|seg| { + let i = (by0 + e) * w4 + bx0 + seg; + 2 * ((info.nnz[i] != 0) | (info.nnz[i - w4] != 0)) as u8 + }); + } + // Macroblock edges still cross into the neighbour, and our own + // coefficients vary per block, so both sides are read per segment. + if mb_x > 0 { + m.v[0] = std::array::from_fn(|seg| { + let qi = (by0 + seg) * w4 + bx0; + let p = Blk::load(info, qi - 1); + if p.inter { bs_inter(&p, &Blk::load(info, qi)) as u8 } else { 4 } + }); + } + if mb_y > 0 { + m.h[0] = std::array::from_fn(|seg| { + let qi = by0 * w4 + bx0 + seg; + let p = Blk::load(info, qi - w4); + if p.inter { bs_inter(&p, &Blk::load(info, qi)) as u8 } else { 4 } + }); + } + m + } + MbKind::Inter => derive_mb(info, mb_x, mb_y, false), + } +} + +/// Derive one macroblock's boundary strengths from the block grids — the entry +/// point for computing them during ENCODE. +/// +/// `info.ref_id` may carry the encoder's raw reference indices (negative for +/// intra) rather than the `NO_REF` sentinel: reference identity is only ever +/// compared between two INTER blocks, which always hold a valid index. +/// PACKED per-macroblock boundary-strength inputs — the x264-shaped layout. +/// +/// Everything one macroblock's derivation needs for its own 16 blocks, contiguous, +/// in raster order (`k = row * 4 + col`). This is the layout `deblock_strength_avx2` +/// works from, and the reason x264 can vectorise a job we currently do 32 times +/// scalar and branchy. +/// +/// Sized by the CEILING PROBE (`examples/bs_layout_ceiling.rs`), which measured, at +/// 720p on synthetic-but-representative content: +/// +/// * cache lines touched per macroblock: **16-20 strided vs 2 packed** +/// * gather cost (cache-warm): **31.1 ns/MB strided vs 12.5 ns/MB packed** (2.49x) +/// +/// Read that second row carefully, because it REFUTED the original justification for +/// this work. The whole derivation costs ~400 ns/MB in context, so eliminating the +/// gather buys only ~19 ns/MB — about 5% of the derivation, ~1% of decode. **The +/// derivation is COMPUTE-bound, not gather-bound**: ~370 ns/MB is the 32 per-edge +/// `bs_inter` evaluations themselves (32 edges x ~20-30 cycles ~= 210-320 ns @ 3 GHz, +/// which matches). So this layout does NOT pay for itself as a memory optimisation. +/// It exists to make the ARITHMETIC vectorisable — `nnz` collapses to shift-and-or on +/// a 16-bit mask, and the motion test becomes i16 subtract/abs/compare across 16 +/// lanes. That distinction decides whether the SIMD stage is worth building, and it +/// is the good case: this codebase's flat SIMD results were all memory-bound kernels, +/// its wins (DCT/SATD) were compute-bound. +/// +/// SINGLE-LIST ONLY. B macroblocks carrying a List-1 slot fall back to the blind +/// path; the two-list rule in `bs1_tile` is not reproduced here. +#[derive(Clone, Copy)] +#[repr(C, align(32))] +pub struct MbPack { + /// Bit `k` set = block `k` has coefficients. The derivation only ever asks + /// "is this block coded", never for the count. + pub nnz_mask: u16, + /// `mb_type` is a per-MACROBLOCK syntax element, so intra-ness is not per-block. + pub inter: bool, + _pad: u8, + /// Quarter-pel motion, per block, SPLIT into x and y planes. + /// + /// Structure-of-arrays on purpose: interleaved `(x,y)` pairs would force the SIMD + /// twin to OR adjacent lanes together (a pairwise reduction), whereas split planes + /// let the x and y compares live in separate registers and OR whole-register. + /// 16 x i16 is exactly one 256-bit load each. + pub mvx: [i16; 16], + pub mvy: [i16; 16], + /// Bit k set = block k carries a List-1 slot. When this is 0 for a macroblock, + /// every internal edge takes the single-list rule and the AVX2 kernel applies; + /// otherwise the two-list set-matching rule runs scalar for that macroblock. + pub l1_used: u16, + pub mvx1: [i16; 16], + pub mvy1: [i16; 16], + pub ref1: [i32; 16], + /// Reference PICTURE IDENTITY per block (`NO_REF` = intra/unused). Kept i32 + /// because the decoder supplies a POC, which must stay comparable across slices + /// whose reference lists differ — a `ref_idx` would compare equal across slices + /// that mean different pictures. + pub ref_id: [i32; 16], +} + +impl BlockInfo<'_> { + /// Block `i`'s List-0 reference identity, applying the optional index map. + #[inline] + fn rid(&self, i: usize) -> i32 { + let r = self.ref_id[i]; + if self.poc0.is_empty() { + r + } else if r >= 0 { + self.poc0.get(r as usize).copied().unwrap_or(NO_REF) + } else { + NO_REF + } + } + + /// Block `i`'s List-1 reference identity (mapped); `NO_REF` when no List-1. + #[inline] + fn rid1(&self, i: usize) -> i32 { + let r = self.ref_id1[i]; + if self.poc1.is_empty() { + r + } else if r >= 0 { + self.poc1.get(r as usize).copied().unwrap_or(NO_REF) + } else { + NO_REF + } + } +} + +impl Default for MbPack { + fn default() -> Self { + Self { + nnz_mask: 0, + inter: false, + _pad: 0, + mvx: [0; 16], + mvy: [0; 16], + l1_used: 0, + mvx1: [0; 16], + mvy1: [0; 16], + ref1: [NO_REF; 16], + ref_id: [NO_REF; 16], + } + } +} + +/// Build the packed records for a whole frame in ONE streaming pass. +/// +/// Each frame-wide array is read once, sequentially and prefetch-friendly, instead of +/// being hit 3600 times at scattered per-macroblock offsets. Returns `None` when the +/// frame carries List-1 data (B slices), which this layout does not model. +pub fn pack_frame(info: &BlockInfo, mb_w: usize, mb_h: usize) -> Option> { + let mut out = Vec::new(); + pack_frame_into(info, mb_w, mb_h, &mut out); + Some(out) +} + +/// [`pack_frame`] into a RECYCLED buffer (Brick: WHYS Part 15 item 1). A fresh +/// `Vec` was ~1.1 MB allocated + first-touch-faulted EVERY frame — the +/// same per-frame-materialization mechanism the banked GridPool brick removed. +/// Each record is built in a local and pushed, so a reused allocation is never +/// pre-filled: one write per byte, no defaults pass, no page faults. +pub fn pack_frame_into(info: &BlockInfo, mb_w: usize, mb_h: usize, out: &mut Vec) { + let has1 = !info.ref_id1.is_empty(); + out.clear(); + out.reserve(mb_w * mb_h); + for mb_y in 0..mb_h { + for mb_x in 0..mb_w { + out.push(pack_mb(info, has1, mb_x, mb_y)); + } + } +} + +/// One macroblock's packed record — the unit of both `pack_frame_into` and the +/// rolling-window precompute pass. +#[inline] +pub fn pack_mb(info: &BlockInfo, has1: bool, mb_x: usize, mb_y: usize) -> MbPack { + let mut rec = MbPack::default(); + let (bx0, by0) = (mb_x * 4, mb_y * 4); + rec.inter = info.inter[by0 * info.w4 + bx0]; + for r in 0..4 { + let row = (by0 + r) * info.w4 + bx0; + for c in 0..4 { + let i = row + c; + let k = r * 4 + c; + if info.nnz[i] != 0 { + rec.nnz_mask |= 1 << k; + } + rec.mvx[k] = info.mv[i].0 as i16; + rec.mvy[k] = info.mv[i].1 as i16; + rec.ref_id[k] = info.rid(i); + if has1 { + let r1 = info.rid1(i); + rec.ref1[k] = r1; + rec.mvx1[k] = info.mv1[i].0 as i16; + rec.mvy1[k] = info.mv1[i].1 as i16; + if r1 != NO_REF { + rec.l1_used |= 1 << k; + } + } + } + } + rec +} + +/// FUSED pack+derive over the whole frame, with a TWO-ROW ROLLING WINDOW of +/// packed records (WHYS Part 16 root-cause lever, bounded form). +/// +/// The frame-buffer pipeline was: pack ALL 3600 records into a ~1.1 MB Vec, +/// then a second interleaved loop re-reads them (plus a per-MB gate ladder) to +/// derive strengths. Here each record is DERIVED the moment it is built — +/// while it and its left/top neighbours are L1-hot — and only `2 × mb_w` +/// records (~50 KB at 720p) ever exist. Output is one `MbBs` (32 B) per +/// macroblock, which `filter_frame` consumes over its existing PRECOMPUTED +/// path, collapsing the per-MB derivation machinery in the hot loop entirely. +/// +/// Byte-identical by the existing oracle chain: `derive_mb_records` is +/// `derive_mb_packed`'s own core (pinned to the tile twin by +/// `packed_matches_tile`), and the precomputed consumer path is pinned by the +/// encoder's use of it. `flat_inter` loop-skips are subsumed by the stored +/// zeros + the consuming loops' all-zero early-outs (documented there). +pub fn precompute_bs_frame(info: &BlockInfo, mb_w: usize, mb_h: usize, out: &mut Vec) { + let has1 = !info.ref_id1.is_empty(); + out.clear(); + out.reserve(mb_w * mb_h); + let mut prev_row: Vec = Vec::with_capacity(mb_w); + let mut cur_row: Vec = Vec::with_capacity(mb_w); + for mb_y in 0..mb_h { + cur_row.clear(); + for mb_x in 0..mb_w { + cur_row.push(pack_mb(info, has1, mb_x, mb_y)); + let cur = &cur_row[mb_x]; + let left = if mb_x > 0 { Some(&cur_row[mb_x - 1]) } else { None }; + let top = if mb_y > 0 { Some(&prev_row[mb_x]) } else { None }; + let mb_t8 = !info.t8x8.is_empty() && info.t8x8[mb_y * mb_w + mb_x]; + let (mut bv, mut bh) = ([[0i32; 4]; 4], [[0i32; 4]; 4]); + derive_mb_records(cur, left, top, mb_t8, &mut bv, &mut bh); + let mut m = MbBs { v: [[0; 4]; 4], h: [[0; 4]; 4] }; + for e in 0..4 { + for sg in 0..4 { + m.v[e][sg] = bv[e][sg] as u8; + m.h[e][sg] = bh[e][sg] as u8; + } + } + out.push(m); + } + std::mem::swap(&mut prev_row, &mut cur_row); + } +} + +thread_local! { + /// Recycled `pack_frame` buffer (~1.1 MB at 720p), `Cell` so `filter_frame` + /// can `take`/`set` without holding a borrow across its whole MB loop. + static PACK_SCRATCH: core::cell::Cell> = const { core::cell::Cell::new(Vec::new()) }; +} + +/// THE KERNEL INTERFACE — the whole motion half of the derivation as two bitmasks. +/// +/// `bit k` of the returned pair answers "does block `k` differ in motion from its +/// LEFT neighbour block `k-1`" and "...from its ABOVE neighbour block `k-4`", using +/// the §8.7.2.1 rule that `bs_inter` applies per edge: +/// +/// ```text +/// differs(a,b) = ref[a] != ref[b] || (ref[a] != NO_REF && (|dmvx| >= 4 || |dmvy| >= 4)) +/// ``` +/// +/// Bits at `k % 4 == 0` (left) and `k < 4` (up) are DON'T-CARE: those edges are +/// macroblock edges, derived separately against the neighbouring record. That is not +/// an accident of convenience — it is what makes the SIMD twin cheap, because the +/// lane positions a within-128-bit-lane shift corrupts are exactly those positions. +/// +/// Collapsing the derivation to masks is the point of the packed layout: the 24 +/// internal edges stop being 24 branchy `bs_inter` calls and become bit tests against +/// these masks OR'd with `nnz_mask`, which is the form `deblock_strength_avx2` works in. +/// Scalar twin of the uniform-motion test — the oracle, and the path on any CPU +/// without AVX2. Short-circuits, which is why the SIMD twin's win concentrates on +/// UNIFORM macroblocks (where this walks all 15 comparisons). +#[inline] +pub fn mb_uniform_scalar(p: &MbPack) -> bool { + p.inter + && (1..16).all(|k| { + p.ref_id[k] == p.ref_id[0] + && p.mvx[k] == p.mvx[0] + && p.mvy[k] == p.mvy[0] + && p.ref1[k] == p.ref1[0] + && p.mvx1[k] == p.mvx1[0] + && p.mvy1[k] == p.mvy1[0] + }) +} + +/// Dispatcher: AVX2 when present, scalar otherwise. `p.inter` is a per-macroblock +/// flag and is checked here, so the kernel only ever answers the 16-lane question. +#[inline] +pub fn mb_uniform(p: &MbPack) -> bool { + #[cfg(all(target_arch = "x86_64", feature = "asm"))] + if p.inter { + if let Some(u) = + rusty_h264_accel::mb_uniform(&p.mvx, &p.mvy, &p.ref_id, &p.mvx1, &p.mvy1, &p.ref1) + { + return u; + } + } + mb_uniform_scalar(p) +} + +#[inline] +pub fn bs_motion_masks_scalar(p: &MbPack) -> (u16, u16) { + let differs = |a: usize, b: usize| -> bool { pk_differs(p, a, p, b) }; + let (mut left, mut up) = (0u16, 0u16); + for k in 0..16usize { + if k % 4 != 0 && differs(k, k - 1) { + left |= 1 << k; + } + if k >= 4 && differs(k, k - 4) { + up |= 1 << k; + } + } + // Don't-care bits are already zero here by construction; the masks are spelled out + // so the SIMD twin (which must clear them explicitly) is comparable on the FULL u16. + (left & 0xEEEE, up & 0xFFF0) +} + +/// Dispatcher: the AVX2 twin when the CPU has it, the scalar oracle otherwise. +/// +/// The scalar version stays the default on any non-AVX2 CPU and remains the +/// reference the SIMD twin is gated against — it is never deleted. +#[inline] +pub fn bs_motion_masks(p: &MbPack) -> (u16, u16) { + #[cfg(feature = "profile")] + { + use std::sync::atomic::Ordering::Relaxed; + census::MASKS_CALLS.fetch_add(1, Relaxed); + if p.l1_used == 0 { + census::MASKS_KERNEL.fetch_add(1, Relaxed); + } else { + census::MASKS_L1.fetch_add(1, Relaxed); + } + } + #[cfg(all(target_arch = "x86_64", feature = "asm"))] + if p.l1_used == 0 { + // Single-list fast kernel: all of P and uni-L0 B macroblocks. + if let Some(m) = rusty_h264_accel::bs_motion_masks(&p.mvx, &p.mvy, &p.ref_id, NO_REF) { + return m; + } + } else { + // TWO-LIST kernel (WHYS Part 16's named lever): the §8.7.2.1 + // set-matching rule vectorized, so B macroblocks with List-1 slots no + // longer fall to the scalar per-edge walk. Gated bit-exact against the + // scalar twin by `bs_motion_masks_two_list_matches_scalar` (accel) and + // the unmasked runtime oracle (`RS_H264_VERIFY_PACKED=1`). + if let Some(m) = rusty_h264_accel::bs_motion_masks_two_list( + &p.mvx, &p.mvy, &p.ref_id, &p.mvx1, &p.mvy1, &p.ref1, NO_REF, + ) { + return m; + } + } + bs_motion_masks_scalar(p) +} + +/// The §8.7.2.1 motion test over packed operands — the EXACT twin of `bs1_tile`, +/// including the two-list set-matching rule (which is order-independent: a block pair +/// whose two reference pictures match after a SWAP is not "different motion"). +/// +/// The single-list fast path fires whenever neither side carries a List-1 slot, which +/// is all of P and most uni-predicted B blocks; only the remainder pays the set match. +#[inline] +fn pk_differs(p: &MbPack, pk: usize, q: &MbPack, qk: usize) -> bool { + let p_has1 = p.ref1[pk] != NO_REF; + let q_has1 = q.ref1[qk] != NO_REF; + if !p_has1 && !q_has1 { + let far = ((p.mvx[pk] - q.mvx[qk]).abs() >= 4) | ((p.mvy[pk] - q.mvy[qk]).abs() >= 4); + return (p.ref_id[pk] != q.ref_id[qk]) | ((p.ref_id[pk] != NO_REF) & far); + } + // Collect the USED reference slots, exactly as `bs1_tile::used` does. + let used = |b: &MbPack, k: usize| { + let mut v = [(0i32, (0i32, 0i32)); 2]; + let mut n = 0usize; + if b.ref_id[k] != NO_REF { + v[n] = (b.ref_id[k], (b.mvx[k] as i32, b.mvy[k] as i32)); + n += 1; + } + if b.ref1[k] != NO_REF { + v[n] = (b.ref1[k], (b.mvx1[k] as i32, b.mvy1[k] as i32)); + n += 1; + } + (v, n) + }; + let (pv, pn) = used(p, pk); + let (qv, qn) = used(q, qk); + if pn != qn { + return true; + } + let far = |a: (i32, i32), b: (i32, i32)| (a.0 - b.0).abs() >= 4 || (a.1 - b.1).abs() >= 4; + match pn { + 0 => false, + 1 => pv[0].0 != qv[0].0 || far(pv[0].1, qv[0].1), + _ => { + let direct = !far(pv[0].1, qv[0].1) && !far(pv[1].1, qv[1].1); + let swap = !far(pv[0].1, qv[1].1) && !far(pv[1].1, qv[0].1); + if pv[0].0 == pv[1].0 { + qv[0].0 != pv[0].0 || qv[1].0 != pv[0].0 || !(direct || swap) + } else if pv[0].0 == qv[0].0 && pv[1].0 == qv[1].0 { + !direct + } else if pv[0].0 == qv[1].0 && pv[1].0 == qv[0].0 { + !swap + } else { + true + } + } + } +} + +#[inline] +fn pk_nz(p: &MbPack, k: usize) -> bool { + (p.nnz_mask >> k) & 1 != 0 +} + +/// `bs_inter` over packed operands — both sides inter, so 3 and 4 are unreachable. +/// Mirrors `bs1_tile`'s single-list fast path exactly. +#[inline] +fn pk_bs_inter(p: &MbPack, pk: usize, q: &MbPack, qk: usize) -> i32 { + if pk_nz(p, pk) | pk_nz(q, qk) { + return 2; + } + let (pr, qr) = (p.ref_id[pk], q.ref_id[qk]); + let _ = (pr, qr); + pk_differs(p, pk, q, qk) as i32 +} + +/// Derive one macroblock's strengths from PACKED records — the byte-identical twin of +/// `derive_mb_bs`, pinned against it by `packed_matches_tile`. +pub fn derive_mb_packed( + packs: &[MbPack], + mb_w: usize, + mb_x: usize, + mb_y: usize, + mb_t8: bool, + bs_v: &mut [[i32; 4]; 4], + bs_h: &mut [[i32; 4]; 4], +) -> bool { + let cur = &packs[mb_y * mb_w + mb_x]; + let left = if mb_x > 0 { Some(&packs[mb_y * mb_w + mb_x - 1]) } else { None }; + let top = if mb_y > 0 { Some(&packs[(mb_y - 1) * mb_w + mb_x]) } else { None }; + derive_mb_records(cur, left, top, mb_t8, bs_v, bs_h) +} + +/// The record-based core of [`derive_mb_packed`]: derive one macroblock's +/// strengths from ITS OWN record plus the left/top neighbours' — the shape the +/// rolling-window precompute pass ([`precompute_bs_frame`]) needs, where only +/// two rows of records exist at a time. +pub fn derive_mb_records( + cur: &MbPack, + left: Option<&MbPack>, + top: Option<&MbPack>, + mb_t8: bool, + bs_v: &mut [[i32; 4]; 4], + bs_h: &mut [[i32; 4]; 4], +) -> bool { + let cur_intra = !cur.inter; + + // Both predicates from the packed record: uniform motion needs no neighbour, and + // "no coefficients" is `nnz_mask == 0` — a single register test replacing a + // 16-block walk. + // + // REFUTED (WHYS Part 16, z=-2.11 REGRESSION, reverted): deriving uniformity + // from `bs_motion_masks` to save "the second kernel call". The two calls are + // ASYMMETRIC: this one is a cheap AVX2 compare-to-block-0 that handles + // two-list B data in vector code, while the masks kernel falls to the SCALAR + // set-matching walk whenever `l1_used != 0` — most B inter MBs. The + // population reaching this function on B frames is uniform-heavy, so the + // "fusion" replaced their one cheap vector call with an expensive scalar + // walk. Do not retry without making the masks kernel two-list-capable first. + let uniform = mb_uniform(cur); + let flat_inter = uniform && cur.nnz_mask == 0; + + if let Some(l) = left { + bs_v[0] = if cur_intra || !l.inter { + [4; 4] + } else { + std::array::from_fn(|seg| pk_bs_inter(l, seg * 4 + 3, cur, seg * 4)) + }; + } + if let Some(t) = top { + bs_h[0] = if cur_intra || !t.inter { + [4; 4] + } else { + std::array::from_fn(|seg| pk_bs_inter(t, 12 + seg, cur, seg)) + }; + } + + if flat_inter { + return true; // internal strengths are 0 by construction + } + // Only the general path consumes these; intra fills constants and uniform motion + // reads coefficients alone. + let masks = if cur_intra || uniform { (0, 0) } else { bs_motion_masks(cur) }; + for be in 1..4usize { + if mb_t8 && (be == 1 || be == 3) { + continue; + } + if cur_intra { + bs_v[be] = [3; 4]; + bs_h[be] = [3; 4]; + } else if uniform { + // Coefficients alone; the whole edge group is a shift-and-or on the mask. + bs_v[be] = std::array::from_fn(|seg| { + 2 * (pk_nz(cur, seg * 4 + be) | pk_nz(cur, seg * 4 + be - 1)) as i32 + }); + bs_h[be] = std::array::from_fn(|seg| { + 2 * (pk_nz(cur, be * 4 + seg) | pk_nz(cur, (be - 1) * 4 + seg)) as i32 + }); + } else { + // The general path, now pure bit tests: coefficients from `nnz_mask`, + // motion from the precomputed masks. No per-edge branching at all. + let (left, up) = masks; + bs_v[be] = std::array::from_fn(|seg| { + let k = seg * 4 + be; + if pk_nz(cur, k) | pk_nz(cur, k - 1) { + 2 + } else { + ((left >> k) & 1) as i32 + } + }); + bs_h[be] = std::array::from_fn(|seg| { + let k = be * 4 + seg; + if pk_nz(cur, k) | pk_nz(cur, k - 4) { + 2 + } else { + ((up >> k) & 1) as i32 + } + }); + } + } + false +} + +/// ONE walk of the macroblock's own 16 blocks yielding BOTH predicates the +/// derivation needs: `(uniform_motion, flat_inter)`. +/// +/// They are the same walk, by construction: +/// ```text +/// uniform_motion = b0.inter AND every block { inter AND same_motion(b0) } +/// flat_inter = uniform_motion AND no block carries coefficients +/// ``` +/// They used to be two independent 16-block scans — and the `uniform_motion` one +/// ran BEFORE `derive_mb_bs`'s `if flat_inter { return }` early-out, so every Skip +/// macroblock paid a full 16-block × 6-compare motion scan whose result was then +/// discarded. The MB-kind census measures Skip at 36.4% (CAVLC) / 65.0% (main) / +/// 57.8% (high) of macroblocks, so that dead scan ran on most of the corpus. +/// +/// Byte-identical to the two-scan form: when the walk breaks early both +/// predicates are false, exactly as both original `.all()` chains would be. +#[inline] +fn scan_uniform_flat(tile: &Tile) -> (bool, bool) { + let b0 = &tile[1][1]; + if !b0.inter { + return (false, false); // intra MB — neither predicate applies + } + let mut any_nz = false; + for r in 1..5 { + for c in 1..5 { + let b = &tile[r][c]; + #[cfg(feature = "profile")] + census::PRED_VISITS.fetch_add(1, std::sync::atomic::Ordering::Relaxed); + if !b.inter || !b.same_motion(b0) { + return (false, false); + } + any_nz |= b.nz; + } + } + (true, !any_nz) +} + +/// The pre-fusion arm, kept verbatim as the measurement baseline AND the oracle. +#[inline] +fn scan_two_pass(tile: &Tile) -> (bool, bool) { + let b0 = &tile[1][1]; + let flat = b0.inter + && (1..5).all(|r| { + (1..5).all(|c| { + let b = &tile[r][c]; + #[cfg(feature = "profile")] + census::PRED_VISITS.fetch_add(1, std::sync::atomic::Ordering::Relaxed); + b.inter && !b.nz && b.same_motion(b0) + }) + }); + let uniform = b0.inter + && (1..5).all(|r| { + (1..5).all(|c| { + #[cfg(feature = "profile")] + census::PRED_VISITS.fetch_add(1, std::sync::atomic::Ordering::Relaxed); + tile[r][c].inter && tile[r][c].same_motion(b0) + }) + }); + (uniform, flat) +} + +/// MEASUREMENT SWITCH — `RS_H264_BS_TWOPASS=1` restores the two independent +/// scans. Both arms live in ONE binary so a bench can alternate them under one +/// thermal state; separate builds on this box drift ~20% run-to-run, which cannot +/// resolve an effect this size. Read once; the branch predicts perfectly. +static BS_TWOPASS: std::sync::atomic::AtomicU8 = std::sync::atomic::AtomicU8::new(0); + +/// Resolve the arm ONCE — hoist this out of any per-macroblock path. +/// +/// It used to be read inside `scan_predicates`, i.e. an atomic load plus a branch +/// on every one of 6.48M macroblocks, present in BOTH arms. That is measurement +/// overhead added in order to take a ~2% measurement, and it is the same mistake +/// this workspace has recorded before (a dedup that replaced cheap work with a +/// dependent load + branch and went backwards). Resolve per frame, pass the bool. +fn bs_twopass() -> bool { + use std::sync::atomic::Ordering; + match BS_TWOPASS.load(Ordering::Relaxed) { + 1 => true, + 2 => false, + _ => { + let on = std::env::var_os("RS_H264_BS_TWOPASS").is_some_and(|v| v != "0"); + BS_TWOPASS.store(if on { 1 } else { 2 }, Ordering::Relaxed); + on + } + } +} + +/// MEASUREMENT SWITCH — `RS_H264_NO_MBKIND=1` ignores producer-supplied classes and +/// forces the blind gather for every macroblock, so the kind-aware brick can be +/// alternated against its own baseline inside ONE binary. Resolved ONCE per frame by +/// the caller and passed down: reading it per macroblock would put an atomic load and +/// a branch in both arms of the very thing being measured (see `bs_twopass`). +static NO_MBKIND: std::sync::atomic::AtomicU8 = std::sync::atomic::AtomicU8::new(0); + +/// CORRECTNESS GATE — `RS_H264_VERIFY_MBKIND=1` derives EVERY kind-classified +/// macroblock BOTH ways and asserts they agree. This is the oracle for the whole +/// brick: a producer that mislabels a macroblock (say, calling a `B_Skip` a `Skip` +/// when direct-derived motion differs per 4x4) changes strengths silently, and the +/// byte-identical corpus gate can only tell you THAT something broke, not where. +/// Run it over the corpus once per producer change; it is far too slow to ship. +fn verify_kind() -> bool { + use std::sync::atomic::Ordering; + static V: std::sync::atomic::AtomicU8 = std::sync::atomic::AtomicU8::new(0); + match V.load(Ordering::Relaxed) { + 1 => true, + 2 => false, + _ => { + let on = std::env::var_os("RS_H264_VERIFY_MBKIND").is_some_and(|v| v != "0"); + V.store(if on { 1 } else { 2 }, Ordering::Relaxed); + on + } + } +} + +/// Compare kind-derived against blind-derived strengths, looking ONLY at the edges +/// the consuming loops actually read. `derive_mb_kind` fills internal groups 1 and 3 +/// even for an 8x8-transform macroblock (whose consumers skip them), so a raw +/// array compare would report a difference that cannot reach a pixel. +#[allow(clippy::too_many_arguments)] +fn verify_kind_matches_blind( + info: &BlockInfo, + mb_x: usize, + mb_y: usize, + mb_t8: bool, + kind: MbKind, + flat_inter: bool, + bs_v: &[[i32; 4]; 4], + bs_h: &[[i32; 4]; 4], +) { + let tile = gather_tile(info, mb_x, mb_y); + let (u, f) = scan_uniform_flat(&tile); + let (mut vv, mut vh) = ([[0i32; 4]; 4], [[0i32; 4]; 4]); + derive_mb_bs(&tile, mb_x, mb_y, f, u, mb_t8, &mut vv, &mut vh); + assert_eq!( + flat_inter, f, + "MB ({mb_x},{mb_y}) kind {kind:?}: flat_inter {flat_inter} but blind derived {f}" + ); + for be in 0..4usize { + if be == 0 { + if mb_x > 0 { + assert_eq!(bs_v[0], vv[0], "MB ({mb_x},{mb_y}) kind {kind:?}: left MB edge"); + } + if mb_y > 0 { + assert_eq!(bs_h[0], vh[0], "MB ({mb_x},{mb_y}) kind {kind:?}: top MB edge"); + } + continue; + } + if flat_inter || (mb_t8 && (be == 1 || be == 3)) { + continue; // consumers skip these entirely + } + assert_eq!(bs_v[be], vv[be], "MB ({mb_x},{mb_y}) kind {kind:?}: v internal edge {be}"); + assert_eq!(bs_h[be], vh[be], "MB ({mb_x},{mb_y}) kind {kind:?}: h internal edge {be}"); + } +} + +/// OPT-IN — `RS_H264_BS_PACKED=1` derives strengths from the packed per-macroblock +/// records instead of the strided gather. Default OFF: the ceiling probe measured the +/// direct memory saving at only ~19 ns/MB of a ~400 ns/MB derivation, so this exists +/// as the ENABLER for a vectorised kernel, not as a memory win in its own right. +/// Resolved once per frame and passed down, never read per macroblock. +/// CORRECTNESS PROBE — `RS_H264_VERIFY_PACKED=1` derives every packed macroblock BOTH +/// ways on real bitstreams and reports the first divergence with its coordinates. The +/// unit oracle passes on a synthetic grid; the corpus does not. This names WHERE. +fn verify_packed() -> bool { + use std::sync::atomic::Ordering; + static V: std::sync::atomic::AtomicU8 = std::sync::atomic::AtomicU8::new(0); + match V.load(Ordering::Relaxed) { + 1 => true, + 2 => false, + _ => { + let on = std::env::var_os("RS_H264_VERIFY_PACKED").is_some_and(|v| v != "0"); + V.store(if on { 1 } else { 2 }, Ordering::Relaxed); + on + } + } +} + +fn bs_packed_on() -> bool { + use std::sync::atomic::Ordering; + static ON: std::sync::atomic::AtomicU8 = std::sync::atomic::AtomicU8::new(0); + match ON.load(Ordering::Relaxed) { + 1 => true, + 2 => false, + _ => { + // DEFAULT ON since 2026-08-02. Polarity written as an explicit opt-OUT so + // it is a decision, not a flag accident: an ABSENT variable means the fast + // path, and only the literal "0" restores the blind gather. + // + // Promoted on three independent interleaved runs (main corpus, 1800 frames + // 720p, pinned, CPU time, ABBA), each with a null arm in the same session: + // packed layout alone median +1.7% 8/9, z = 2.33 + // + both AVX2 kernels median +6.7% 11/15, z = 1.81 + // + both AVX2 kernels median +3.3% 12/15, z = 2.32 <- deciding run + // null arms 1.000 / 1.039 z = -1.13 / 0.38 + // The two full-stack runs pool to 23/30, z = 2.92. + // + // Honest shape: single-run medians ranged 1.7-6.7% because this box drifts, + // so the WIN RATE carries the verdict; the median is the effect-size + // estimate, not the proof. + let off = std::env::var_os("RS_H264_BS_PACKED").is_some_and(|v| v == "0"); + ON.store(if off { 2 } else { 1 }, Ordering::Relaxed); + !off + } + } +} + +fn kind_gate_off() -> bool { + use std::sync::atomic::Ordering; + match NO_MBKIND.load(Ordering::Relaxed) { + 1 => true, + 2 => false, + _ => { + let off = std::env::var_os("RS_H264_NO_MBKIND").is_some_and(|v| v != "0"); + NO_MBKIND.store(if off { 1 } else { 2 }, Ordering::Relaxed); + off + } + } +} + +#[inline] +fn scan_predicates(tile: &Tile, two_pass: bool) -> (bool, bool) { + if two_pass { + scan_two_pass(tile) + } else { + scan_uniform_flat(tile) + } +} + +pub fn derive_mb(info: &BlockInfo, mb_x: usize, mb_y: usize, mb_t8: bool) -> MbBs { + let tile = gather_tile(info, mb_x, mb_y); + let (uniform_motion, flat_inter) = scan_predicates(&tile, bs_twopass()); + let (mut bs_v, mut bs_h) = ([[0i32; 4]; 4], [[0i32; 4]; 4]); + derive_mb_bs(&tile, mb_x, mb_y, flat_inter, uniform_motion, mb_t8, &mut bs_v, &mut bs_h); + let pack = |a: [[i32; 4]; 4]| a.map(|e| e.map(|x| x as u8)); + MbBs { v: pack(bs_v), h: pack(bs_h) } +} + +/// The 5×5 neighbourhood an MB's edges can reach: row/col 0 are the top and left +/// neighbour blocks, rows/cols 1..=4 the MB's own 4×4 grid. Entries outside the +/// picture stay `Default` and are never read (the frame-edge groups are skipped). +type Tile = [[Blk; 5]; 5]; + +/// Gather the tile for macroblock (`mb_x`, `mb_y`). +fn gather_tile(info: &BlockInfo, mb_x: usize, mb_y: usize) -> Tile { + let mut t: Tile = Default::default(); + let (bx0, by0) = (mb_x * 4, mb_y * 4); + // The MB's own blocks: four contiguous runs of four. + for r in 0..4 { + let row = (by0 + r) * info.w4 + bx0; + for c in 0..4 { + t[r + 1][c + 1] = Blk::load(info, row + c); + } + } + if mb_x > 0 { + for r in 0..4 { + t[r + 1][0] = Blk::load(info, (by0 + r) * info.w4 + bx0 - 1); + } + } + if mb_y > 0 { + let row = (by0 - 1) * info.w4 + bx0; + for c in 0..4 { + t[0][c + 1] = Blk::load(info, row + c); + } + } + // `mb_type` is a per-macroblock syntax element, so every 4×4 block of a + // macroblock shares its intra/inter status. `derive_mb_bs` depends on this to + // replace per-edge intra tests with per-macroblock constant fills. + debug_assert!( + (1..5).all(|r| (1..5).all(|c| t[r][c].inter == t[1][1].inter)), + "macroblock ({mb_x},{mb_y}) mixes intra and inter 4x4 blocks" + ); + t +} + +/// Selects the boundary-strength derivation. Default (and shipped path) is the +/// per-MB TILE; `RS_H264_DEBLOCK_BRANCHY=1` restores the original per-edge +/// derivation straight off the frame arrays. +/// +/// This exists so both arms live in ONE binary and a benchmark can alternate +/// them under the same thermal state — comparing separate builds on this machine +/// has ~20% run-to-run drift, which cannot resolve the effect being measured. +/// It doubles as the fallback switch. Read once; the branch predicts perfectly. +static BS_MODE: std::sync::atomic::AtomicU8 = std::sync::atomic::AtomicU8::new(0); + +fn branchless_bs() -> bool { + use std::sync::atomic::Ordering; + match BS_MODE.load(Ordering::Relaxed) { + 1 => true, + 2 => false, + _ => { + let branchy = std::env::var_os("RS_H264_DEBLOCK_BRANCHY").is_some_and(|v| v != "0"); + BS_MODE.store(if branchy { 2 } else { 1 }, Ordering::Relaxed); + !branchy + } + } +} + +/// Whether the per-MB tile path is active. +fn deblock_tile() -> bool { + branchless_bs() +} + +/// DEFAULT OFF. Deriving boundary strengths in the encode loop makes the +/// deblocking stage 1.4-1.7x faster but does NOT reduce total encode time: the +/// block grids were never cold (~90 KB at CIF, L2-resident), so the derivation +/// costs the same in a streaming pass, and the encode loop's contended working +/// set makes it cost MORE there — measured, the loop grew about twice the +/// derivation's own cost. Kept behind this switch with its tests, because the +/// machinery is what a future commit-time derivation (values still in registers, +/// no grid re-read) would build on. +static BS_PRECOMP: std::sync::atomic::AtomicU8 = std::sync::atomic::AtomicU8::new(0); + +/// Whether callers may supply precomputed boundary strengths (the encoder path). +pub fn precomputed_bs_enabled() -> bool { + BS_PRECOMP.load(std::sync::atomic::Ordering::Relaxed) != 0 +} + +/// Toggle the precomputed-strength path so a benchmark can ALTERNATE the two +/// designs inside ONE process. +#[doc(hidden)] +pub fn set_precomputed_bs(on: bool) { + BS_PRECOMP.store(on as u8, std::sync::atomic::Ordering::Relaxed); +} + +/// Force the deblocking boundary-strength arm at runtime. Exists so a benchmark +/// can ALTERNATE the arms inside one process under one thermal state; comparing +/// separate builds cannot resolve the effect on this machine. +#[doc(hidden)] +pub fn set_branchless_bs(on: bool) { + BS_MODE.store(if on { 1 } else { 2 }, std::sync::atomic::Ordering::Relaxed); +} + +impl BlockInfo<'_> { + #[inline] + fn at(&self, bx: usize, by: usize) -> usize { + by * self.w4 + bx + } + + /// Boundary strength between left/above block `p` and current block `q` + /// (spec §8.7.2.1). `mb_edge` is true on macroblock boundaries. + /// + /// Written branchlessly on purpose. Real content mixes intra/inter, coded and + /// uncoded blocks, and per-block motion, so the natural short-circuit form + /// (`if intra … else if nnz … else if motion …`) mispredicts on nearly every + /// 4×4 edge: the anatomy bench measures the identical code at ~240 ns/MB on + /// uniform data and ~515 ns/MB once the block state varies, which is the + /// whole of our gap to x264 here (x264 derives bS with a branchless SIMD + /// kernel). Evaluating all three candidates costs a few extra loads and beats + /// paying a ~15-cycle mispredict per edge. + #[inline] + fn bs(&self, p: usize, q: usize, mb_edge: bool) -> i32 { + if branchless_bs() { + self.bs_branchless(p, q, mb_edge) + } else { + self.bs_branchy(p, q, mb_edge) + } + } + + /// The original short-circuit form, kept as the A/B arm and the fallback. + /// Identical output to [`Self::bs_branchless`] by construction. + fn bs_branchy(&self, p: usize, q: usize, mb_edge: bool) -> i32 { + if !self.inter[p] || !self.inter[q] { + if mb_edge { + 4 + } else { + 3 + } + } else if self.nnz[p] > 0 || self.nnz[q] > 0 { + 2 + } else if self.inter_bs1(p, q) { + 1 + } else { + 0 + } + } + + #[inline] + fn bs_branchless(&self, p: usize, q: usize, mb_edge: bool) -> i32 { + let intra = !(self.inter[p] & self.inter[q]); + let nz = (self.nnz[p] | self.nnz[q]) != 0; + let moved = self.inter_bs1(p, q); + let intra_bs = if mb_edge { 4 } else { 3 }; + // Priority intra > coefficients > motion, as selects rather than branches. + let motion_bs = moved as i32; // 1 or 0 + let non_intra = if nz { 2 } else { motion_bs }; + if intra { + intra_bs + } else { + non_intra + } + } + + /// Whether two residual-free inter blocks get boundary strength 1: they use + /// different reference pictures, a different number of motion vectors, or a + /// motion vector differs by ≥ 1 full sample (matched by reference picture, so + /// the same picture in different lists is recognised). Spec §8.7.2.1. + fn inter_bs1(&self, p: usize, q: usize) -> bool { + // Single-list fast path (P and I slices — `ref_id1` empty). This is the + // overwhelmingly common case, and it collapses to two comparisons: the + // general path below builds a two-slot [(ref, mv); 2] array per side and + // matches on the slot count, which the anatomy bench showed dominates + // deblocking. Exactly equivalent here: with one list, `pn`/`qn` are just + // "is the slot used", so a differing ref_id covers both the + // different-count and different-picture cases, and two unused slots give + // pn == qn == 0 => false. + if self.ref_id1.is_empty() { + // Branchless (see `bs`): `|`/`&` rather than `||`/`&&` so there is no + // data-dependent branch here either. The single `is_empty` test above + // is uniform across a whole frame and predicts perfectly. + let (rp, rq) = (self.ref_id[p], self.ref_id[q]); + let (a, b) = (self.mv[p], self.mv[q]); + let far = ((a.0 - b.0).abs() >= 4) | ((a.1 - b.1).abs() >= 4); + // Differing refs ⇒ bS 1 (this also covers "one slot used, one not", + // the general path's differing-count case). Both unused ⇒ 0. + return (rp != rq) | ((rp != NO_REF) & far); + } + // (reference id, motion vector) for each used prediction slot. + let used = |i: usize| { + let mut v = [(0i32, (0i32, 0i32)); 2]; + let mut n = 0; + if self.ref_id[i] != NO_REF { + v[n] = (self.ref_id[i], self.mv[i]); + n += 1; + } + // `ref_id1` may be empty (P frames have no List-1 — the caller skips + // building it, since every entry would be NO_REF anyway). + if !self.ref_id1.is_empty() && self.ref_id1[i] != NO_REF { + v[n] = (self.ref_id1[i], self.mv1[i]); + n += 1; + } + (v, n) + }; + let (pv, pn) = used(p); + let (qv, qn) = used(q); + if pn != qn { + return true; // different number of motion vectors + } + let far = |a: (i32, i32), b: (i32, i32)| (a.0 - b.0).abs() >= 4 || (a.1 - b.1).abs() >= 4; + match pn { + 0 => false, + 1 => pv[0].0 != qv[0].0 || far(pv[0].1, qv[0].1), + _ => { + // Two references each: the picture *sets* must match, and the + // motion vectors for corresponding pictures must be close. If both + // slots are the same picture, either pairing is acceptable. + let direct = !far(pv[0].1, qv[0].1) && !far(pv[1].1, qv[1].1); + let swap = !far(pv[0].1, qv[1].1) && !far(pv[1].1, qv[0].1); + if pv[0].0 == pv[1].0 { + qv[0].0 != pv[0].0 || qv[1].0 != pv[0].0 || !(direct || swap) + } else if pv[0].0 == qv[0].0 && pv[1].0 == qv[1].0 { + !direct + } else if pv[0].0 == qv[1].0 && pv[1].0 == qv[0].0 { + !swap + } else { + true // different picture sets + } + } + } + } +} + +/// Applies the deblocking filter in place to a fully-reconstructed frame. `qp` +/// is the (constant) luma QP, `qpc` the chroma QP, and `info` supplies the +/// per-block state used to derive boundary strengths (for an all-intra frame +/// this reduces to the fixed 4/3 strengths). +/// Edge thresholds `(α, β, tc0[bS-1])` for a given averaged QP and the slice's +/// filter offsets (spec §8.7.2.2): α/tc0 indexed by `indexA`, β by `indexB`. +#[inline] +fn thresholds(qpav: i32, offset_a: i32, offset_b: i32) -> (i32, i32, [i32; 3]) { + let ia = (qpav + offset_a).clamp(0, 51) as usize; + let ib = (qpav + offset_b).clamp(0, 51) as usize; + (ALPHA[ia], BETA[ib], TC0[ia]) +} + +#[allow(clippy::too_many_arguments)] +pub fn filter_frame( + y: &mut [u8], + u: &mut [u8], + v: &mut [u8], + mb_w: usize, + mb_h: usize, + mb_qp: &[u8], + chroma_qp_offset: i32, + offset_a: i32, + offset_b: i32, + info: &BlockInfo, +) { + filter_frame_rows(y, u, v, mb_w, mb_h, 0..mb_h, mb_qp, chroma_qp_offset, offset_a, offset_b, info) +} + +/// [`filter_frame`] restricted to macroblock rows `rows` — the row-interleave +/// campaign's unit (docs/row-interleave-plan.md R3): the decoder filters row +/// `r` the moment it finishes decoding, spec raster order preserved exactly. +#[allow(clippy::too_many_arguments)] +pub fn filter_frame_rows( + y: &mut [u8], + u: &mut [u8], + v: &mut [u8], + mb_w: usize, + mb_h: usize, + rows: core::ops::Range, + mb_qp: &[u8], + chroma_qp_offset: i32, + offset_a: i32, + offset_b: i32, + info: &BlockInfo, +) { + let _g = crate::prof::scope(crate::prof::Stage::Deblock); + let cw = mb_w * 16; + let ccw = mb_w * 8; + // Per-edge QP: deblock strength uses the average of the two adjacent + // macroblocks' QPy (spec §8.7.2). For an internal edge both sides share the + // current MB's QP. Chroma averages the two MBs' QPc. + let qpy = |mx: usize, my: usize| mb_qp[my * mb_w + mx] as i32; + let qpc = |qpy_val: i32| { + crate::predict::chroma_qp((qpy_val + chroma_qp_offset).clamp(0, 51) as u8) as i32 + }; + // Arms resolved ONCE per frame, never per macroblock (see `bs_twopass`). + let two_pass = bs_twopass(); + let kind_off = kind_gate_off(); + let verify_kinds = verify_kind(); + // ONE streaming pass over the frame arrays, not 3600 scattered gathers. `None` + // when the frame carries List-1 data (B slices), which MbPack does not model — + // those macroblocks keep the blind path. + let scratch = PACK_SCRATCH.take(); + let packs: Option> = if bs_packed_on() && info.bs.is_empty() && deblock_tile() { + let mut buf = scratch; + { + let _pg = crate::prof::scope(crate::prof::Stage::DebPack); + pack_frame_into(info, mb_w, mb_h, &mut buf); + } + Some(buf) + } else { + PACK_SCRATCH.set(scratch); + None + }; + + for mb_y in rows { + for mb_x in 0..mb_w { + // `t8x8` may be empty (no MB uses the 8×8 transform — Baseline); treat + // an empty grid as all-false so the caller can skip allocating it. + let mb_t8 = !info.t8x8.is_empty() && info.t8x8[mb_y * mb_w + mb_x]; + // A "flat inter MB" — every 4x4 inter, zero nnz, one (ref, mv) pair (e.g. + // any skip MB) — has bs = 0 on ALL its internal edges by §8.7.2.1 (no + // coefficients, same reference, identical motion), so the six internal + // edge groups can be skipped wholesale. Byte-identical control flow. + // Gather the MB's 4×4 block state once (see `Blk`). Every boundary + // strength below then reads the tile instead of the strided frame + // arrays. Only valid for a single reference list; B slices keep the + // original per-edge path untouched. + // `deblock_tile()` selects the arm so a bench can alternate the whole + // brick (tile vs the original per-edge derivation) in one process. + // Precomputed strengths short-circuit the gather AND the derivation; + // flat_inter and the t8x8 skips are already baked into the stored + // zeros, which the all-zero early-out below handles identically. + let _dg = crate::prof::scope(crate::prof::Stage::DebDerive); + let precomputed = !info.bs.is_empty(); + // H-33: the tile arm now carries the two-list B rule (`bs1_tile`), so + // real-world B frames no longer fall back to the strided per-edge path. + let use_tile = !precomputed && deblock_tile(); + let have_bs = precomputed || use_tile; + + // KIND-AWARE FAST PATH. When the producer has classified this + // macroblock, its strengths follow from syntax and the 24-block + // neighbourhood gather is not needed at all: Intra reads NOTHING, Skip + // reads 9 blocks, InterUniform reads 16 nnz bytes. `Inter` and UNSET + // fall through to the blind path below, so an unclassified macroblock + // costs speed and never correctness. + // + // The gather is skipped by CONSTRUCTION here rather than by an early-out + // inside it — building the 5x5 `Tile` at all is an 800-byte + // default-initialisation before 24 of its 25 entries are overwritten. + let fast_kind = if use_tile && !kind_off { + match info.kind.get(mb_y * mb_w + mb_x).copied().and_then(MbKind::from_u8) { + Some(k) if k != MbKind::Inter => Some(k), + _ => None, + } + } else { + None + }; + + let blind_tile = use_tile && fast_kind.is_none() && packs.is_none(); + // Declared before the predicate chain: the packed derivation produces + // `flat_inter` and the strengths in ONE traversal, so it cannot be split + // across the two chains the way the tile path is. + let mut bs_v = [[0i32; 4]; 4]; + let mut bs_h = [[0i32; 4]; 4]; + let packed_mb = packs.as_ref().filter(|_| use_tile && fast_kind.is_none()); + // MATERIALISE THE TILE ONLY ON THE BLIND PATH. Writing + // `else { Default::default() }` here cost an 800-byte zero-init of the + // 5x5 `Tile` on every CLASSIFIED macroblock — i.e. this brick removed a + // gather and added ~4 GB of memset, and measured 1.2-17.0% SLOWER in + // 4/4 pairs. `Option` keeps the fast path free of it entirely. + let tile = if blind_tile { Some(gather_tile(info, mb_x, mb_y)) } else { None }; + + // ONE walk yields both predicates — see `scan_uniform_flat`. The + // non-tile arm has no `uniform_motion` consumer (it derives per-edge + // off the frame arrays), so it keeps returning `flat_inter` alone. + let mut uniform_motion = false; + let flat_inter = if precomputed { + false // the stored zeros already encode it + } else if let Some(k) = fast_kind { + match k { + // No coefficients and one shared (ref, mv): every internal + // strength is 0 by construction. + MbKind::Skip => true, + // CAUGHT BY THE ORACLE: a single-partition inter macroblock + // with NO coefficients is flat too — uniform motion means the + // blind predicate reduces to exactly "no block has nnz". + // Hardcoding `false` here was pixel-identical (the strengths + // are all 0 either way) but made the consuming loops walk the + // internal edge groups instead of skipping them, throwing away + // part of the win. 16 contiguous nnz bytes — the same data + // `derive_mb_kind` already reads for this class. + MbKind::InterUniform => { + let (bx0, by0) = (mb_x * 4, mb_y * 4); + (0..4).all(|r| { + (0..4).all(|c| info.nnz[(by0 + r) * info.w4 + bx0 + c] == 0) + }) + } + _ => false, + } + } else if let Some(pk) = packed_mb { + #[cfg(feature = "profile")] + census::PACKED_MB.fetch_add(1, std::sync::atomic::Ordering::Relaxed); + let pflat = derive_mb_packed(pk, mb_w, mb_x, mb_y, mb_t8, &mut bs_v, &mut bs_h); + if verify_packed() { + // UNMASKED: all 32 strengths, not just the ones the consuming + // loops read. A masked oracle can pass while the corpus diverges. + let t = gather_tile(info, mb_x, mb_y); + let (u, f) = scan_uniform_flat(&t); + let (mut tv, mut th) = ([[0i32; 4]; 4], [[0i32; 4]; 4]); + derive_mb_bs(&t, mb_x, mb_y, f, u, mb_t8, &mut tv, &mut th); + assert_eq!(pflat, f, "MB ({mb_x},{mb_y}) t8={mb_t8}: flat_inter"); + assert_eq!(bs_v, tv, "MB ({mb_x},{mb_y}) t8={mb_t8} flat={f}: bs_v"); + assert_eq!(bs_h, th, "MB ({mb_x},{mb_y}) t8={mb_t8} flat={f}: bs_h"); + } + pflat + } else if blind_tile { + let (u, f) = scan_predicates(tile.as_ref().unwrap(), two_pass); + uniform_motion = u; + f + } else { + let b0 = info.at(mb_x * 4, mb_y * 4); + let mut ok = info.inter[b0]; + if ok { + let (r0, m0) = (info.ref_id[b0], info.mv[b0]); + let has1 = !info.ref_id1.is_empty(); + let (r10, m10) = if has1 { (info.ref_id1[b0], info.mv1[b0]) } else { (NO_REF, (0, 0)) }; + 'scan: for by in 0..4 { + for bx in 0..4 { + let i = info.at(mb_x * 4 + bx, mb_y * 4 + by); + if !info.inter[i] + || info.nnz[i] != 0 + || info.ref_id[i] != r0 + || info.mv[i] != m0 + || (has1 && (info.ref_id1[i] != r10 || info.mv1[i] != m10)) + { + ok = false; + break 'scan; + } + } + } + } + ok + }; + // ---- boundary strengths for the whole macroblock, derived ONCE ---- + // The chroma edge groups are CO-LOCATED with luma edges 0 and 2 and + // derive identical strengths (pinned by `chroma_bs_matches_luma`), so + // deriving them in the chroma loops recomputed 16 of the 48 per-MB + // strengths. Guards mirror the consuming loops exactly, so nothing is + // derived that was not derived before; edges left at zero are exactly + // the edges those loops skip. + if packed_mb.is_some() { + // Already written by `derive_mb_packed` above: unlike the tile path, + // the packed derivation produces `flat_inter` AND the strengths in one + // traversal, so it cannot be split across the two chains. + } else if precomputed { + let m = &info.bs[mb_y * mb_w + mb_x]; + for e in 0..4 { + for sg in 0..4 { + bs_v[e][sg] = m.v[e][sg] as i32; + bs_h[e][sg] = m.h[e][sg] as i32; + } + } + } else if let Some(k) = fast_kind { + // Write i32 strengths straight into the consuming arrays. Going via + // `derive_mb_kind`'s packed `MbBs` cost 32 u8->i32 stores per + // classified macroblock that the blind path never pays — pure + // addition on the path that is supposed to be cheaper. + derive_mb_kind_into(info, mb_x, mb_y, k, &mut bs_v, &mut bs_h); + if verify_kinds { + verify_kind_matches_blind( + info, mb_x, mb_y, mb_t8, k, flat_inter, &bs_v, &bs_h, + ); + } + } else if blind_tile { + derive_mb_bs( + tile.as_ref().unwrap(), + mb_x, + mb_y, + flat_inter, + uniform_motion, + mb_t8, + &mut bs_v, + &mut bs_h, + ); + } + drop(_dg); + // ---- luma vertical edges (block columns 0..4) ---- + for be in 0..4usize { + if be == 0 && mb_x == 0 { + continue; + } + if flat_inter && be != 0 { + continue; // internal bs all 0 (flat inter MB) + } + // 8×8-transform MBs: internal 4×4 edges (be 1, 3) aren't filtered. + if mb_t8 && (be == 1 || be == 3) { + continue; + } + let mb_edge = be == 0; + let mut bs4 = [0i32; 4]; + if have_bs { + bs4 = bs_v[be]; + } else { + let abx = mb_x * 4 + be; + for (seg, b) in bs4.iter_mut().enumerate() { + let aby = mb_y * 4 + seg; + *b = info.bs(info.at(abx - 1, aby), info.at(abx, aby), mb_edge); + } + } + if bs4.iter().all(|&b| b == 0) { + continue; + } + // Thresholds AFTER the all-zero early-out: on real content most + // edges filter nothing, and computing α/β/tc0 (two clamps plus + // three table loads, and a neighbour QP read on MB edges) for an + // edge we are about to skip is pure waste. + let qpav = if mb_edge { + (qpy(mb_x - 1, mb_y) + qpy(mb_x, mb_y) + 1) >> 1 + } else { + qpy(mb_x, mb_y) + }; + let (alpha_y, beta_y, tc0a) = thresholds(qpav, offset_a, offset_b); + let tc0_luma = |bs: i32| if (1..4).contains(&bs) { tc0a[bs as usize - 1] } else { 0 }; + let x = mb_x * 16 + be * 4; + // Vertical edge via openh264's transpose → V-filter → transpose-back + // (the `DeblockLumaLt4H` wrapper). tc per 4-row segment (−1 = skip). + #[cfg(accel)] + { + let base = mb_y * 16 * cw + (x - 4); // p3 column, top row + if bs4.iter().all(|&b| b == 4) { + rusty_h264_accel::deblock_luma_eq4_h(&mut y[base..], cw, alpha_y, beta_y); + } else { + let tc: [i8; 4] = std::array::from_fn(|i| { + if (1..4).contains(&bs4[i]) { tc0_luma(bs4[i]) as i8 } else { -1 } + }); + rusty_h264_accel::deblock_luma_lt4_h(&mut y[base..], cw, alpha_y, beta_y, &tc); + } + } + #[cfg(not(accel))] + for (seg, &bs) in bs4.iter().enumerate() { + if bs == 0 { + continue; + } + let tc0 = tc0_luma(bs); + for row in 0..4 { + let yy = mb_y * 16 + seg * 4 + row; + let line = Line { base: yy * cw + x, step: 1 }; + filter_luma_line(y, &line, bs, alpha_y, beta_y, tc0); + } + } + } + // ---- luma horizontal edges (block rows 0..4) ---- + for be in 0..4usize { + if be == 0 && mb_y == 0 { + continue; + } + if flat_inter && be != 0 { + continue; // internal bs all 0 (flat inter MB) + } + if mb_t8 && (be == 1 || be == 3) { + continue; + } + let mb_edge = be == 0; + let mut bs4 = [0i32; 4]; + if have_bs { + bs4 = bs_h[be]; + } else { + let aby = mb_y * 4 + be; + for (seg, b) in bs4.iter_mut().enumerate() { + let abx = mb_x * 4 + seg; + *b = info.bs(info.at(abx, aby - 1), info.at(abx, aby), mb_edge); + } + } + if bs4.iter().all(|&b| b == 0) { + continue; + } + // Thresholds after the early-out — see the vertical-edge note. + let qpav = if mb_edge { + (qpy(mb_x, mb_y - 1) + qpy(mb_x, mb_y) + 1) >> 1 + } else { + qpy(mb_x, mb_y) + }; + let (alpha_y, beta_y, tc0a) = thresholds(qpav, offset_a, offset_b); + let tc0_luma = |bs: i32| if (1..4).contains(&bs) { tc0a[bs as usize - 1] } else { 0 }; + let yy = mb_y * 16 + be * 4; + // openh264's DeblockLumaLt4V/Eq4V filter the whole 16-column horizontal + // edge at once (p/q vertical; plane 16-aligned via AlignedBytes). + // bit-identical spec filter; tc per 4-column segment (−1 = skip). + #[cfg(accel)] + { + let base = (yy - 4) * cw + mb_x * 16; // p3 row (4 rows above q0) + if bs4.iter().all(|&b| b == 4) { + rusty_h264_accel::deblock_luma_eq4_v(&mut y[base..], cw, alpha_y, beta_y); + } else { + let tc: [i8; 4] = std::array::from_fn(|i| { + if (1..4).contains(&bs4[i]) { tc0_luma(bs4[i]) as i8 } else { -1 } + }); + rusty_h264_accel::deblock_luma_lt4_v(&mut y[base..], cw, alpha_y, beta_y, &tc); + } + } + #[cfg(not(accel))] + for (seg, &bs) in bs4.iter().enumerate() { + if bs == 0 { + continue; + } + let tc0 = tc0_luma(bs); + for col in 0..4 { + let x = mb_x * 16 + seg * 4 + col; + let line = Line { base: yy * cw + x, step: cw as isize }; + filter_luma_line(y, &line, bs, alpha_y, beta_y, tc0); + } + } + } + // ---- chroma edges (8×8): bS taken from the co-located luma edge ---- + // The chroma `tc` is the spec `tc0+1` (no ap/aq adjustment); bS varies per + // 2-chroma-sample segment (= one co-located luma 4×4 block). + #[cfg(accel)] + { + let tc0_of = |arr: [i32; 3], bs: i32| if (1..4).contains(&bs) { arr[bs as usize - 1] } else { 0 }; + // Chroma thresholds are derived per edge, AFTER that edge is known + // to filter. Deriving all three sets up front cost three + // `chroma_qp` lookups and three table lookups on every macroblock, + // including the majority whose chroma edges are all bS 0. + let chroma_thresholds = |mb_edge: bool, nx: usize, ny: usize| { + let cur = qpc(qpy(mb_x, mb_y)); + let q = if mb_edge { (qpc(qpy(nx, ny)) + cur + 1) >> 1 } else { cur }; + thresholds(q, offset_a, offset_b) + }; + // vertical chroma edges → DeblockChromaLt4H/Eq4H (Cb+Cr together). + for cxe in [0usize, 4] { + if cxe == 0 && mb_x == 0 { + continue; + } + if flat_inter && cxe != 0 { + continue; // internal bs all 0 (flat inter MB) + } + let mb_edge = cxe == 0; + let x = mb_x * 8 + cxe; + let mut bs4 = [0i32; 4]; + if have_bs { + bs4 = bs_v[cxe / 2]; // co-located luma edge, already derived + } else { + let abx = mb_x * 4 + cxe / 2; + for (seg, b) in bs4.iter_mut().enumerate() { + let aby = mb_y * 4 + seg; + *b = info.bs(info.at(abx - 1, aby), info.at(abx, aby), mb_edge); + } + } + if bs4.iter().all(|&b| b == 0) { + continue; + } + let (alpha_c, beta_c, tc0c) = + chroma_thresholds(mb_edge, mb_x.wrapping_sub(1), mb_y); + let base = (mb_y * 8) * ccw + (x - 2); // p1 (2 cols left of q0) + if bs4.iter().all(|&b| b == 4) { + rusty_h264_accel::deblock_chroma_eq4_h(&mut u[base..], &mut v[base..], ccw, alpha_c, beta_c); + } else { + let tc: [i8; 4] = std::array::from_fn(|i| { + if (1..4).contains(&bs4[i]) { tc0_of(tc0c, bs4[i]) as i8 + 1 } else { 0 } + }); + rusty_h264_accel::deblock_chroma_lt4_h(&mut u[base..], &mut v[base..], ccw, alpha_c, beta_c, &tc); + } + } + // horizontal chroma edges → DeblockChromaLt4V/Eq4V. + for cye in [0usize, 4] { + if cye == 0 && mb_y == 0 { + continue; + } + if flat_inter && cye != 0 { + continue; // internal bs all 0 (flat inter MB) + } + let mb_edge = cye == 0; + let yy = mb_y * 8 + cye; + let mut bs4 = [0i32; 4]; + if have_bs { + bs4 = bs_h[cye / 2]; // co-located luma edge, already derived + } else { + let aby = mb_y * 4 + cye / 2; + for (seg, b) in bs4.iter_mut().enumerate() { + let abx = mb_x * 4 + seg; + *b = info.bs(info.at(abx, aby - 1), info.at(abx, aby), mb_edge); + } + } + if bs4.iter().all(|&b| b == 0) { + continue; + } + let (alpha_c, beta_c, tc0c) = + chroma_thresholds(mb_edge, mb_x, mb_y.wrapping_sub(1)); + let base = (yy - 2) * ccw + mb_x * 8; // p1 (2 rows above q0) + if bs4.iter().all(|&b| b == 4) { + rusty_h264_accel::deblock_chroma_eq4_v(&mut u[base..], &mut v[base..], ccw, alpha_c, beta_c); + } else { + let tc: [i8; 4] = std::array::from_fn(|i| { + if (1..4).contains(&bs4[i]) { tc0_of(tc0c, bs4[i]) as i8 + 1 } else { 0 } + }); + rusty_h264_accel::deblock_chroma_lt4_v(&mut u[base..], &mut v[base..], ccw, alpha_c, beta_c, &tc); + } + } + } + #[cfg(not(accel))] + { + // Chroma edge thresholds use the average of the two MBs' QPc. + let cur_qpc = qpc(qpy(mb_x, mb_y)); + let (alpha_cv, beta_cv, tc0cv) = if mb_x > 0 { + thresholds((qpc(qpy(mb_x - 1, mb_y)) + cur_qpc + 1) >> 1, offset_a, offset_b) + } else { + (0, 0, [0; 3]) // unused (cxe==0 skipped at frame edge) + }; + let (alpha_ch, beta_ch, tc0ch) = if mb_y > 0 { + thresholds((qpc(qpy(mb_x, mb_y - 1)) + cur_qpc + 1) >> 1, offset_a, offset_b) + } else { + (0, 0, [0; 3]) + }; + let (alpha_ci, beta_ci, tc0ci) = thresholds(cur_qpc, offset_a, offset_b); + let tc0_of = |arr: [i32; 3], bs: i32| if (1..4).contains(&bs) { arr[bs as usize - 1] } else { 0 }; + // bS from the co-located luma edge — the STORED strengths when + // available, exactly like the accel arm and the luma loops above. + // This is not just the shared-derivation saving: on the precomputed + // path the caller's view may carry NO syntax grids at all (the E2 + // worker's `PixelCtx::filter_row` passes `inter: &[]`), so live + // derivation here is an out-of-bounds panic, not a slow path. + let chroma_bs = |stored: &[[i32; 4]; 4], edge: usize, vertical: bool, mb_edge: bool| -> [i32; 4] { + if have_bs { + return stored[edge / 2]; // co-located luma edge, already derived + } + let mut bs4 = [0i32; 4]; + for (seg, b) in bs4.iter_mut().enumerate() { + let (abx, aby) = if vertical { + (mb_x * 4 + edge / 2, mb_y * 4 + seg) + } else { + (mb_x * 4 + seg, mb_y * 4 + edge / 2) + }; + let (p, q) = if vertical { + (info.at(abx - 1, aby), info.at(abx, aby)) + } else { + (info.at(abx, aby - 1), info.at(abx, aby)) + }; + *b = info.bs(p, q, mb_edge); + } + bs4 + }; + for plane in [&mut *u, &mut *v] { + for cxe in [0usize, 4] { + if cxe == 0 && mb_x == 0 { + continue; + } + if flat_inter && cxe != 0 { + continue; + } + let mb_edge = cxe == 0; + // MB-left edge uses the cross-MB chroma avg; internal uses the MB's own. + let (alpha_c, beta_c, tc0c) = + if mb_edge { (alpha_cv, beta_cv, tc0cv) } else { (alpha_ci, beta_ci, tc0ci) }; + let bs4 = chroma_bs(&bs_v, cxe, true, mb_edge); + let x = mb_x * 8 + cxe; + for row in 0..8 { + // Segment = the co-located luma block row (2 chroma rows each). + let bs = bs4[(row * 2) / 4]; + if bs == 0 { + continue; + } + let yy = mb_y * 8 + row; + let line = Line { base: yy * ccw + x, step: 1 }; + filter_chroma_line(plane, &line, bs, alpha_c, beta_c, tc0_of(tc0c, bs)); + } + } + for cye in [0usize, 4] { + if cye == 0 && mb_y == 0 { + continue; + } + if flat_inter && cye != 0 { + continue; + } + let mb_edge = cye == 0; + let (alpha_c, beta_c, tc0c) = + if mb_edge { (alpha_ch, beta_ch, tc0ch) } else { (alpha_ci, beta_ci, tc0ci) }; + let bs4 = chroma_bs(&bs_h, cye, false, mb_edge); + let yy = mb_y * 8 + cye; + for col in 0..8 { + // Segment = the co-located luma block column. + let bs = bs4[(col * 2) / 4]; + if bs == 0 { + continue; + } + let line = Line { base: yy * ccw + (mb_x * 8 + col), step: ccw as isize }; + filter_chroma_line(plane, &line, bs, alpha_c, beta_c, tc0_of(tc0c, bs)); + } + } + } + } + } + } + if let Some(buf) = packs { + PACK_SCRATCH.set(buf); + } +} + +#[cfg(test)] +mod tests { + use super::*; + + /// The two-list AVX2 masks kernel vs the scalar set-matching twin, over + /// randomized two-list inputs. Unused slots deliberately carry GARBAGE + /// motion: the scalar twin ignores it via slot compaction, and the kernel + /// must neutralize it — equality here proves the neutralization. + #[cfg(all(target_arch = "x86_64", feature = "asm"))] + #[test] + fn two_list_masks_match_scalar() { + let mut seed = 0x2545_F491u32; + let mut rnd = move || { + seed ^= seed << 13; + seed ^= seed >> 17; + seed ^= seed << 5; + seed + }; + for _ in 0..50_000 { + let mut p = MbPack::default(); + p.inter = true; + for k in 0..16 { + let r = rnd(); + p.ref_id[k] = match r & 3 { + 0 => NO_REF, + 1 => 10, + 2 => 20, + _ => 30, + }; + p.ref1[k] = match (r >> 2) & 3 { + 0 => NO_REF, + 1 => 10, + 2 => 40, + _ => 20, + }; + // Motion near the ±4 threshold; unused slots get garbage on purpose. + p.mvx[k] = ((r >> 4) % 11) as i16 - 5; + p.mvy[k] = ((r >> 8) % 11) as i16 - 5; + p.mvx1[k] = ((r >> 12) % 11) as i16 - 5; + p.mvy1[k] = ((r >> 16) % 11) as i16 - 5; + if p.ref1[k] != NO_REF { + p.l1_used |= 1 << k; + } + } + let scalar = bs_motion_masks_scalar(&p); + let simd = rusty_h264_accel::bs_motion_masks_two_list( + &p.mvx, &p.mvy, &p.ref_id, &p.mvx1, &p.mvy1, &p.ref1, NO_REF, + ) + .expect("AVX2 present on the test box"); + assert_eq!(simd, scalar, "l1_used={:04x} ref0={:?} ref1={:?}", p.l1_used, p.ref_id, p.ref1); + } + } + + /// The two boundary-strength arms must be the same function. `bs_branchless` + /// is the shipped path and `bs_branchy` the fallback/A-B arm, so any + /// divergence would silently change the filtered reconstruction — and, since + /// the reconstruction is the inter prediction reference, the bitstream. + #[test] + fn bs_arms_agree() { + let (w4, h4) = (16usize, 16usize); + let n = w4 * h4; + // Deterministic pseudo-random block state covering every branch: intra vs + // inter, coded vs uncoded, matching vs differing refs, near vs far motion. + let mut st = 0x9e3779b9u32; + let mut rnd = || { + st ^= st << 13; + st ^= st >> 17; + st ^= st << 5; + st + }; + let mut inter = vec![false; n]; + let mut nnz = vec![0u8; n]; + let mut mv = vec![(0i32, 0i32); n]; + let mut ref_id = vec![0i32; n]; + for i in 0..n { + let r = rnd(); + inter[i] = r & 3 != 0; + nnz[i] = if r & 0x30 != 0 { (r >> 8 & 15) as u8 } else { 0 }; + // Span the |Δ| >= 4 boundary in both components. + mv[i] = (((r >> 12) & 15) as i32 - 8, ((r >> 16) & 15) as i32 - 8); + ref_id[i] = if inter[i] { ((r >> 20) & 3) as i32 } else { NO_REF }; + } + let info = BlockInfo { + inter: &inter, + nnz: &nnz, + mv: &mv, + ref_id: &ref_id, + mv1: &[], + ref_id1: &[], + w4, + t8x8: &[], + poc0: &[], + poc1: &[], + bs: &[], kind: &[], + }; + let mut checked = 0; + for q in 0..n { + for &p in &[q.saturating_sub(1), q.saturating_sub(w4)] { + for mb_edge in [false, true] { + assert_eq!( + info.bs_branchy(p, q, mb_edge), + info.bs_branchless(p, q, mb_edge), + "bS mismatch at p={p} q={q} mb_edge={mb_edge}" + ); + checked += 1; + } + } + } + assert!(checked > 1000, "expected broad coverage, checked {checked}"); + } +} + +#[cfg(test)] +mod tile_tests { + use super::*; + + /// The per-MB tile must reproduce the frame-array indexing exactly. This is + /// where a transcription slip would hide: the tile's (row, col) origin is the + /// top-left NEIGHBOUR, so every edge lookup is offset by one, and chroma edge + /// groups index it at half the luma rate. + #[test] + fn tile_matches_frame_indexing() { + let (mb_w, mb_h) = (5usize, 4usize); + let w4 = mb_w * 4; + let n = w4 * mb_h * 4; + let mut st = 0xdeadbeefu32; + let mut rnd = || { + st ^= st << 13; + st ^= st >> 17; + st ^= st << 5; + st + }; + let mut inter = vec![false; n]; + let mut nnz = vec![0u8; n]; + let mut mv = vec![(0i32, 0i32); n]; + let mut ref_id = vec![0i32; n]; + for i in 0..n { + let r = rnd(); + inter[i] = r & 3 != 0; + nnz[i] = if r & 0x30 != 0 { (r >> 8 & 15) as u8 } else { 0 }; + mv[i] = (((r >> 12) & 15) as i32 - 8, ((r >> 16) & 15) as i32 - 8); + ref_id[i] = if inter[i] { ((r >> 20) & 3) as i32 } else { NO_REF }; + } + let info = BlockInfo { + inter: &inter, nnz: &nnz, mv: &mv, ref_id: &ref_id, + poc0: &[], + poc1: &[], + mv1: &[], ref_id1: &[], w4, t8x8: &[], bs: &[], kind: &[], + }; + + let mut checked = 0; + for mb_y in 0..mb_h { + for mb_x in 0..mb_w { + let tile = gather_tile(&info, mb_x, mb_y); + for be in 0..4 { + let mb_edge = be == 0; + if mb_edge && mb_x == 0 { + continue; + } + // luma vertical + let abx = mb_x * 4 + be; + for seg in 0..4 { + let aby = mb_y * 4 + seg; + assert_eq!( + info.bs(info.at(abx - 1, aby), info.at(abx, aby), mb_edge), + bs_tile(&tile[seg + 1][be], &tile[seg + 1][be + 1], mb_edge), + "luma V mb=({mb_x},{mb_y}) be={be} seg={seg}" + ); + checked += 1; + } + } + for be in 0..4 { + let mb_edge = be == 0; + if mb_edge && mb_y == 0 { + continue; + } + let aby = mb_y * 4 + be; + for seg in 0..4 { + let abx = mb_x * 4 + seg; + assert_eq!( + info.bs(info.at(abx, aby - 1), info.at(abx, aby), mb_edge), + bs_tile(&tile[be][seg + 1], &tile[be + 1][seg + 1], mb_edge), + "luma H mb=({mb_x},{mb_y}) be={be} seg={seg}" + ); + checked += 1; + } + } + // chroma groups index the tile at half the luma rate + for cxe in [0usize, 4] { + let mb_edge = cxe == 0; + if mb_edge && mb_x == 0 { + continue; + } + let abx = mb_x * 4 + cxe / 2; + for seg in 0..4 { + let aby = mb_y * 4 + seg; + assert_eq!( + info.bs(info.at(abx - 1, aby), info.at(abx, aby), mb_edge), + bs_tile(&tile[seg + 1][cxe / 2], &tile[seg + 1][cxe / 2 + 1], mb_edge), + "chroma V mb=({mb_x},{mb_y}) cxe={cxe} seg={seg}" + ); + checked += 1; + } + } + for cye in [0usize, 4] { + let mb_edge = cye == 0; + if mb_edge && mb_y == 0 { + continue; + } + let aby = mb_y * 4 + cye / 2; + for seg in 0..4 { + let abx = mb_x * 4 + seg; + assert_eq!( + info.bs(info.at(abx, aby - 1), info.at(abx, aby), mb_edge), + bs_tile(&tile[cye / 2][seg + 1], &tile[cye / 2 + 1][seg + 1], mb_edge), + "chroma H mb=({mb_x},{mb_y}) cye={cye} seg={seg}" + ); + checked += 1; + } + } + } + } + assert!(checked > 800, "coverage too low: {checked}"); + } +} + +#[cfg(test)] +mod chroma_bs_tests { + use super::*; + + /// A chroma edge group is CO-LOCATED with a luma edge group — chroma edge 0 + /// with luma edge 0, chroma edge 4 with luma edge 2 — and derives the + /// identical boundary strengths, because bS is a property of the 4×4 block + /// pair, not of the plane. This test is the licence for the derivation to run + /// once per luma edge and be reused by chroma; without it, 16 of the 48 + /// per-macroblock derivations are recomputes. + #[test] + fn chroma_bs_matches_luma() { + let (mb_w, mb_h) = (5usize, 4usize); + let w4 = mb_w * 4; + let n = w4 * mb_h * 4; + let mut st = 0x1badb002u32; + let mut rnd = || { + st ^= st << 13; + st ^= st >> 17; + st ^= st << 5; + st + }; + let (mut inter, mut nnz) = (vec![false; n], vec![0u8; n]); + let (mut mv, mut ref_id) = (vec![(0i32, 0i32); n], vec![0i32; n]); + for i in 0..n { + let r = rnd(); + inter[i] = r & 3 != 0; + nnz[i] = if r & 0x30 != 0 { (r >> 8 & 15) as u8 } else { 0 }; + mv[i] = (((r >> 12) & 15) as i32 - 8, ((r >> 16) & 15) as i32 - 8); + ref_id[i] = if inter[i] { ((r >> 20) & 3) as i32 } else { NO_REF }; + } + let info = BlockInfo { + inter: &inter, nnz: &nnz, mv: &mv, ref_id: &ref_id, + poc0: &[], + poc1: &[], + mv1: &[], ref_id1: &[], w4, t8x8: &[], bs: &[], kind: &[], + }; + let mut checked = 0; + for mb_y in 0..mb_h { + for mb_x in 0..mb_w { + let tile = gather_tile(&info, mb_x, mb_y); + for (cxe, be) in [(0usize, 0usize), (4, 2)] { + let mb_edge = cxe == 0; + for seg in 0..4 { + // vertical: chroma column cxe/2 == luma column `be` + assert_eq!( + bs_tile(&tile[seg + 1][cxe / 2], &tile[seg + 1][cxe / 2 + 1], mb_edge), + bs_tile(&tile[seg + 1][be], &tile[seg + 1][be + 1], mb_edge), + "V mb=({mb_x},{mb_y}) cxe={cxe} seg={seg}" + ); + // horizontal: chroma row cye/2 == luma row `be` + assert_eq!( + bs_tile(&tile[cxe / 2][seg + 1], &tile[cxe / 2 + 1][seg + 1], mb_edge), + bs_tile(&tile[be][seg + 1], &tile[be + 1][seg + 1], mb_edge), + "H mb=({mb_x},{mb_y}) cye={cxe} seg={seg}" + ); + checked += 2; + } + } + } + } + assert!(checked > 300, "coverage too low: {checked}"); + } +} + +#[cfg(test)] +mod derive_tests { + use super::*; + + /// `derive_mb_bs` must reproduce the per-edge derivation exactly. It replaces + /// per-edge intra tests with per-macroblock constant fills, so the test data + /// must respect the invariant that licences it: intra/inter is uniform across + /// a macroblock's 16 blocks. + /// The PACKED derivation must reproduce the tile derivation exactly — same + /// strengths AND the same `flat_inter`. This is the oracle for the whole + /// packed-layout brick: the packed path is a different traversal of the same + /// rule, so a byte-identical corpus run can tell you THAT it broke but not where, + /// and (as Brick 2 proved) a pixel-identical mistake can hide in `flat_inter` + /// while silently costing the optimisation it was built for. + /// The SIMD twin must equal the scalar oracle on the FULL u16, not merely on the + /// bits the derivation reads — the don't-care lanes are masked to zero in both so + /// a lane-boundary mistake cannot hide behind "that bit is unused anyway". + /// + /// Exercises the cases the kernel's shifts are sensitive to: NO_REF blocks, refs + /// that differ, motion exactly at the |d| == 4 threshold (the `>= 4` boundary), + /// and large opposite-signed vectors where a saturating subtract could go wrong. + /// The uniform-motion SIMD twin must equal the scalar oracle. Cases are built to + /// straddle the decision: genuinely uniform macroblocks, ones differing in exactly + /// ONE lane of ONE plane (the case a broadcast-compare gets wrong if a plane is + /// dropped), and ones differing only on List-1. + #[test] + fn mb_uniform_simd_matches_scalar() { + let mut st = 0x51ed270bu32; + let mut rnd = || { + st ^= st << 13; + st ^= st >> 17; + st ^= st << 5; + st + }; + for case in 0..6000 { + let mut p = MbPack::default(); + p.inter = case % 7 != 0; // exercise the intra short-circuit too + for k in 0..16 { + p.ref_id[k] = 3; + p.mvx[k] = 7; + p.mvy[k] = -9; + p.ref1[k] = if case % 3 == 0 { NO_REF } else { 5 }; + p.mvx1[k] = 2; + p.mvy1[k] = -4; + } + // Perturb exactly one lane of one plane, often — that is the boundary. + if case % 2 == 0 { + let k = 1 + (rnd() % 15) as usize; + match rnd() % 6 { + 0 => p.ref_id[k] += 1, + 1 => p.mvx[k] += 1, + 2 => p.mvy[k] += 1, + 3 => p.ref1[k] = p.ref1[k].wrapping_add(1), + 4 => p.mvx1[k] += 1, + _ => p.mvy1[k] += 1, + } + } + assert_eq!( + mb_uniform(&p), + mb_uniform_scalar(&p), + "case {case}: uniform SIMD != scalar" + ); + } + } + + #[test] + fn bs_motion_masks_simd_matches_scalar() { + let mut st = 0x9e3779b9u32; + let mut rnd = || { + st ^= st << 13; + st ^= st >> 17; + st ^= st << 5; + st + }; + for case in 0..4000 { + let mut p = MbPack::default(); + p.inter = true; + for k in 0..16 { + let r = rnd(); + p.ref_id[k] = match case % 4 { + 0 => (r & 1) as i32, // two references, frequent changes + 1 => 7, // all identical + 2 if r & 7 == 0 => NO_REF, // scattered intra/unused + _ => (r & 3) as i32, + }; + // Straddle the >= 4 threshold deliberately, and include extremes. + p.mvx[k] = match case % 3 { + 0 => ((r >> 3) & 7) as i16 - 4, + 1 => ((r >> 3) & 0x7fff) as i16 - 16384, + _ => ((r >> 3) & 1) as i16 * 4, + }; + p.mvy[k] = match case % 3 { + 0 => ((r >> 9) & 7) as i16 - 4, + 1 => ((r >> 9) & 0x7fff) as i16 - 16384, + _ => ((r >> 9) & 1) as i16 * 4, + }; + } + let want = bs_motion_masks_scalar(&p); + let got = bs_motion_masks(&p); + assert_eq!( + got, want, + "case {case}: SIMD (left={:#06x} up={:#06x}) != scalar (left={:#06x} up={:#06x})", + got.0, got.1, want.0, want.1 + ); + } + } + + #[test] + fn packed_matches_tile() { + let (mb_w, mb_h) = (6usize, 5usize); + let w4 = mb_w * 4; + let n = w4 * mb_h * 4; + let mut st = 0x1234abcdu32; + let mut rnd = || { + st ^= st << 13; + st ^= st >> 17; + st ^= st << 5; + st + }; + let (mut inter, mut nnz) = (vec![false; n], vec![0u8; n]); + let (mut mv, mut ref_id) = (vec![(0i32, 0i32); n], vec![0i32; n]); + for my in 0..mb_h { + for mx in 0..mb_w { + // intra/inter is a per-MACROBLOCK property; the packed record stores + // one flag per macroblock and depends on that invariant. + let mb_inter = rnd() & 3 != 0; + // Deliberately include macroblocks that are uniform (exercising the + // `uniform`/`flat_inter` fast paths) as well as fully varied ones. + let uniform_mb = rnd() & 1 == 0; + let (ur, umv) = ((rnd() & 1) as i32, ((rnd() & 7) as i32 - 4, (rnd() & 7) as i32 - 4)); + let zero_coeffs = rnd() & 1 == 0; + for by in 0..4 { + for bx in 0..4 { + let i = (my * 4 + by) * w4 + mx * 4 + bx; + let r = rnd(); + inter[i] = mb_inter; + nnz[i] = if uniform_mb && zero_coeffs { + 0 + } else if r & 0x30 != 0 { + (r >> 8 & 15) as u8 + } else { + 0 + }; + if mb_inter { + ref_id[i] = if uniform_mb { ur } else { (r >> 12 & 1) as i32 }; + mv[i] = if uniform_mb { + umv + } else { + ((r >> 16 & 15) as i32 - 8, (r >> 20 & 15) as i32 - 8) + }; + } else { + ref_id[i] = NO_REF; + mv[i] = (0, 0); + } + } + } + } + } + // A List-1 plane too, so the two-slot set-matching rule is exercised — that + // rule is order-independent (a pair matching after a SWAP is NOT different + // motion), which a single-list grid cannot test at all. + let (mut mv1, mut ref_id1) = (vec![(0i32, 0i32); n], vec![NO_REF; n]); + for my in 0..mb_h { + for mx in 0..mb_w { + let mb_bi = rnd() & 1 == 0; // some macroblocks bi-predicted + for by in 0..4 { + for bx in 0..4 { + let i = (my * 4 + by) * w4 + mx * 4 + bx; + let r = rnd(); + if inter[i] && mb_bi && r & 3 != 0 { + ref_id1[i] = (r >> 2 & 1) as i32; + mv1[i] = ((r >> 4 & 15) as i32 - 8, (r >> 8 & 15) as i32 - 8); + } + } + } + } + } + for (tag, m1, r1) in [ + ("single-list", &[][..], &[][..]), + ("two-list", &mv1[..], &ref_id1[..]), + ] { + let info = BlockInfo { + inter: &inter, nnz: &nnz, mv: &mv, ref_id: &ref_id, + poc0: &[], + poc1: &[], + mv1: m1, ref_id1: r1, w4, t8x8: &[], bs: &[], kind: &[], + }; + let packs = pack_frame(&info, mb_w, mb_h).expect("frame packs"); + let _ = tag; + + let mut checked = 0usize; + for mb_y in 0..mb_h { + for mb_x in 0..mb_w { + let tile = gather_tile(&info, mb_x, mb_y); + let (uniform, flat) = scan_uniform_flat(&tile); + for &mb_t8 in &[false, true] { + let (mut tv, mut th) = ([[0i32; 4]; 4], [[0i32; 4]; 4]); + derive_mb_bs(&tile, mb_x, mb_y, flat, uniform, mb_t8, &mut tv, &mut th); + + let (mut pv, mut ph) = ([[0i32; 4]; 4], [[0i32; 4]; 4]); + let pflat = + derive_mb_packed(&packs, mb_w, mb_x, mb_y, mb_t8, &mut pv, &mut ph); + + assert_eq!( + pflat, flat, + "MB ({mb_x},{mb_y}) t8={mb_t8}: flat_inter packed={pflat} tile={flat}" + ); + // Compare only the edges the consuming loops actually read — the + // same masking the kind-vs-blind oracle uses, for the same reason. + for be in 0..4usize { + if be == 0 { + if mb_x > 0 { + assert_eq!(pv[0], tv[0], "MB ({mb_x},{mb_y}) left MB edge"); + } + if mb_y > 0 { + assert_eq!(ph[0], th[0], "MB ({mb_x},{mb_y}) top MB edge"); + } + continue; + } + if flat || (mb_t8 && (be == 1 || be == 3)) { + continue; + } + assert_eq!(pv[be], tv[be], "MB ({mb_x},{mb_y}) t8={mb_t8} v edge {be}"); + assert_eq!(ph[be], th[be], "MB ({mb_x},{mb_y}) t8={mb_t8} h edge {be}"); + } + checked += 1; + } + } + } + assert_eq!(checked, mb_w * mb_h * 2, "every macroblock checked both t8 ways ({tag})"); + } + } + + #[test] + fn derive_matches_per_edge() { + let (mb_w, mb_h) = (6usize, 5usize); + let w4 = mb_w * 4; + let n = w4 * mb_h * 4; + let mut st = 0xfeedfaceu32; + let mut rnd = || { + st ^= st << 13; + st ^= st >> 17; + st ^= st << 5; + st + }; + let (mut inter, mut nnz) = (vec![false; n], vec![0u8; n]); + let (mut mv, mut ref_id) = (vec![(0i32, 0i32); n], vec![0i32; n]); + for my in 0..mb_h { + for mx in 0..mb_w { + // one intra/inter decision per MACROBLOCK, as the bitstream has + let mb_inter = rnd() & 3 != 0; + for by in 0..4 { + for bx in 0..4 { + let i = (my * 4 + by) * w4 + mx * 4 + bx; + let r = rnd(); + inter[i] = mb_inter; + nnz[i] = if r & 0x30 != 0 { (r >> 8 & 15) as u8 } else { 0 }; + mv[i] = (((r >> 12) & 15) as i32 - 8, ((r >> 16) & 15) as i32 - 8); + ref_id[i] = if mb_inter { ((r >> 20) & 3) as i32 } else { NO_REF }; + } + } + } + } + let info = BlockInfo { + inter: &inter, nnz: &nnz, mv: &mv, ref_id: &ref_id, + poc0: &[], + poc1: &[], + mv1: &[], ref_id1: &[], w4, t8x8: &[], bs: &[], kind: &[], + }; + + // The fused walk must agree with the two independent scans it replaced, on + // every macroblock of this pseudo-random grid — the reference test the + // fusion is gated on. Checked here rather than in its own test so it rides + // the same varied intra/inter/nnz/motion mix. + for mb_y in 0..mb_h { + for mb_x in 0..mb_w { + let tile = gather_tile(&info, mb_x, mb_y); + assert_eq!( + scan_uniform_flat(&tile), + scan_two_pass(&tile), + "fused predicate walk disagrees with the two-scan oracle at ({mb_x},{mb_y})" + ); + } + } + + let mut checked = 0; + for mb_y in 0..mb_h { + for mb_x in 0..mb_w { + let tile = gather_tile(&info, mb_x, mb_y); + // the flat-inter predicate exactly as `filter_frame` computes it + let b0 = &tile[1][1]; + let flat = b0.inter + && (1..5).all(|r| (1..5).all(|c| { + let b = &tile[r][c]; + b.inter && !b.nz && b.same_motion(b0) + })); + // …and `uniform_motion` likewise, derived here INDEPENDENTLY of + // `scan_uniform_flat` so this stays an oracle for the fused walk + // rather than a consumer of it. + let uniform = b0.inter + && (1..5).all(|r| { + (1..5).all(|c| tile[r][c].inter && tile[r][c].same_motion(b0)) + }); + for &mb_t8 in &[false, true] { + let (mut bv, mut bh) = ([[0i32; 4]; 4], [[0i32; 4]; 4]); + derive_mb_bs(&tile, mb_x, mb_y, flat, uniform, mb_t8, &mut bv, &mut bh); + for be in 0..4usize { + let mb_edge = be == 0; + let skip_internal = + !mb_edge && (flat || (mb_t8 && (be == 1 || be == 3))); + for seg in 0..4 { + let want_v = if skip_internal || (mb_edge && mb_x == 0) { + 0 + } else { + bs_tile(&tile[seg + 1][be], &tile[seg + 1][be + 1], mb_edge) + }; + let want_h = if skip_internal || (mb_edge && mb_y == 0) { + 0 + } else { + bs_tile(&tile[be][seg + 1], &tile[be + 1][seg + 1], mb_edge) + }; + assert_eq!(bv[be][seg], want_v, "V mb=({mb_x},{mb_y}) be={be} seg={seg} t8={mb_t8}"); + assert_eq!(bh[be][seg], want_h, "H mb=({mb_x},{mb_y}) be={be} seg={seg} t8={mb_t8}"); + checked += 2; + } + } + } + } + } + assert!(checked > 1500, "coverage too low: {checked}"); + } +} diff --git a/vendor/rusty_h264-common/src/inter.rs b/vendor/rusty_h264-common/src/inter.rs new file mode 100644 index 0000000..e138655 --- /dev/null +++ b/vendor/rusty_h264-common/src/inter.rs @@ -0,0 +1,1899 @@ +//! Inter prediction primitives: motion compensation and motion-vector +//! prediction. Shared by the encoder (reconstruction) and decoder so the two +//! agree bit-for-bit. Motion vectors are in quarter-pel units; phase 4b uses +//! the integer part only (full-pel), with the 6-tap/bilinear sub-pel filters +//! arriving in 4c. + +/// Median of three values (`a + b + c − min − max`). +#[inline] +pub fn median3(a: i32, b: i32, c: i32) -> i32 { + a + b + c - a.min(b).min(c) - a.max(b).max(c) +} + +/// A motion-vector predictor neighbor: whether the neighbor block is available +/// (inside the picture/decoded), its motion vector, and its reference index +/// (`-1` for intra/unavailable neighbors, which contribute a zero MV with a +/// non-matching reference). +#[derive(Clone, Copy)] +pub struct MvNeighbor { + pub available: bool, + pub mv: (i32, i32), + pub ref_idx: i32, +} + +impl MvNeighbor { + pub const NONE: MvNeighbor = MvNeighbor { + available: false, + mv: (0, 0), + ref_idx: -1, + }; +} + +/// Median motion-vector prediction for a partition (spec §8.4.1.3.1), against +/// the current partition's reference `cur_ref`. `a`/`b`/`c` are the left, above, +/// and above-right neighbors. If exactly one neighbor shares `cur_ref`, its MV is +/// the predictor; otherwise the component-wise median is used. +pub fn predict_mv(a: MvNeighbor, b: MvNeighbor, c: MvNeighbor, cur_ref: i32) -> (i32, i32) { + // Per-neighbor (mv, refIdx): a usable inter neighbor keeps its mv+ref, else + // a zero MV with ref −1 (never matches a valid `cur_ref` ≥ 0). + let resolve = |n: MvNeighbor| -> ((i32, i32), i32) { + if n.available && n.ref_idx >= 0 { + (n.mv, n.ref_idx) + } else { + ((0, 0), -1) + } + }; + let (mva, ra) = resolve(a); + let (mut mvb, mut rb) = resolve(b); + let (mut mvc, mut rc) = resolve(c); + + // If both B and C are unavailable but A is available, B and C take A. + if !b.available && !c.available && a.available { + mvb = mva; + rb = ra; + mvc = mva; + rc = ra; + } + + let matches = (ra == cur_ref) as i32 + (rb == cur_ref) as i32 + (rc == cur_ref) as i32; + if matches == 1 { + if ra == cur_ref { + mva + } else if rb == cur_ref { + mvb + } else { + mvc + } + } else { + (median3(mva.0, mvb.0, mvc.0), median3(mva.1, mvb.1, mvc.1)) + } +} + +/// Directional MV prediction for a sub-partition (spec §8.4.1.3.2) against the +/// partition's reference `cur_ref`. `mode` is the inter `mb_type` (0 = 16×16, +/// 1 = 16×8, 2 = 8×16). 16×8/8×16 use a specific neighbor directly when it shares +/// `cur_ref`; otherwise (and always for 16×16) the median. +pub fn predict_partition_mv( + mode: u8, + part: usize, + a: MvNeighbor, + b: MvNeighbor, + c: MvNeighbor, + cur_ref: i32, +) -> (i32, i32) { + let m = |n: MvNeighbor| n.available && n.ref_idx == cur_ref; + match (mode, part) { + (1, 0) if m(b) => b.mv, // 16×8 top → above + (1, 1) if m(a) => a.mv, // 16×8 bottom → left + (2, 0) if m(a) => a.mv, // 8×16 left → left + (2, 1) if m(c) => c.mv, // 8×16 right → above-right + _ => predict_mv(a, b, c, cur_ref), + } +} + +/// Inter `mb_type` → luma partition regions `(x, y, w, h)` in samples. +pub fn inter_partitions(mode: u8) -> &'static [(usize, usize, usize, usize)] { + match mode { + 1 => &[(0, 0, 16, 8), (0, 8, 16, 8)], // P_16x8 + 2 => &[(0, 0, 8, 16), (8, 0, 8, 16)], // P_8x16 + // P_8x8: four 8×8 sub-macroblocks in raster (decode_p8x8) order, each its + // own MV. (Sub-8×8 shapes 8×4/4×8/4×4 within an 8×8 are a further split.) + 3 => &[(0, 0, 8, 8), (8, 0, 8, 8), (0, 8, 8, 8), (8, 8, 8, 8)], + _ => &[(0, 0, 16, 16)], // P_L0_16x16 + } +} + +/// Reference sample with edge clamping. +/// +/// Bounds-SAFE: a decoder driven by a malformed stream can reach here with `(cw, ch)` +/// that do not match the plane it was handed, and every caller's "interior" test is +/// written against `cw`/`ch` rather than the slice length. In bounds this is identical +/// to a direct index; out of bounds it yields 0 instead of panicking. (Found by the +/// fuzzer the moment CABAC became the default — the CABAC parse produces wilder +/// vectors on mutated input than CAVLC did, so this path had never been reached.) +#[inline] +fn at(reference: &[u8], cw: usize, ch: usize, x: isize, y: isize) -> i32 { + let xx = x.clamp(0, cw as isize - 1) as usize; + let yy = y.clamp(0, ch as isize - 1) as usize; + reference.get(yy * cw + xx).copied().unwrap_or(0) as i32 +} + +#[inline] +fn clip_u8(v: i32) -> i32 { + v.clamp(0, 255) +} + +/// Per-pixel quarter-pel luma sample (spec §8.4.2.2.1) — the readable reference +/// kept as the bit-exactness oracle for the block-kernel MC below. +#[cfg(test)] +fn luma_sample(reference: &[u8], cw: usize, ch: usize, ix: isize, iy: isize, fx: i32, fy: i32) -> i32 { + let g = |dx: isize, dy: isize| at(reference, cw, ch, ix + dx, iy + dy); + if fx == 0 && fy == 0 { + return g(0, 0); + } + 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); + 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); + let b = || clip_u8((hor6(0) + 16) >> 5); + let h = || clip_u8((ver6(0) + 16) >> 5); + let m = || clip_u8((ver6(1) + 16) >> 5); + let s = || clip_u8((hor6(1) + 16) >> 5); + let j = || { + let j1 = hor6(-2) - 5 * hor6(-1) + 20 * hor6(0) + 20 * hor6(1) - 5 * hor6(2) + hor6(3); + clip_u8((j1 + 512) >> 10) + }; + match (fx, fy) { + (1, 0) => (g(0, 0) + b() + 1) >> 1, + (2, 0) => b(), + (3, 0) => (g(1, 0) + b() + 1) >> 1, + (0, 1) => (g(0, 0) + h() + 1) >> 1, + (1, 1) => (b() + h() + 1) >> 1, + (2, 1) => (b() + j() + 1) >> 1, + (3, 1) => (b() + m() + 1) >> 1, + (0, 2) => h(), + (1, 2) => (h() + j() + 1) >> 1, + (2, 2) => j(), + (3, 2) => (j() + m() + 1) >> 1, + (0, 3) => (g(0, 1) + h() + 1) >> 1, + (1, 3) => (h() + s() + 1) >> 1, + (2, 3) => (j() + s() + 1) >> 1, + _ => (m() + s() + 1) >> 1, + } +} + +// ---- Block-level luma MC, mirroring openh264 `mc.cpp` (`McHorVerNN_c`) ---- +// +// openh264 computes each half-pel plane once per block (not per pixel) and +// averages clipped planes for the quarter positions. Our `luma_sample` recomputed +// the 6-tap for every pixel; these kernels compute each plane once. Bit-identical: +// the 6-tap is separable with exact (un-rounded) integer intermediates, so +// horizontal-then-vertical equals vertical-then-horizontal, and the clamped tile +// reproduces `at()` exactly. + +/// Max luma interpolation tile: a 16×16 block plus the 6-tap halo (2 left/up, +/// 3 right/down) → 21×21. +const LUMA_TILE: usize = 21; + +/// Per-thread scratch for the sub-pel MC path. +/// +/// These three buffers used to be created — and therefore **zero-initialised** — +/// inside every `mc_luma` call, and the tile was additionally returned *by value*. +/// That is ~1.4 KB of `memset` plus a 441-byte move per call, paid identically +/// whether the block is 16×16 (256 useful samples) or 4×4 (16). Profiling put +/// `inter-mc` at 166 s of a 266 s quality-preset encode over 991 M calls, and a +/// block-size sweep showed a 4×4 sub-pel call costing *more* than a 16×16 one +/// (248 vs 172 ns) — i.e. the cost was the per-call buffers, not the filter. +/// +/// Hoisting them to thread-local scratch makes that setup once per thread instead +/// of once per candidate. Byte-identical: both `luma_tile_into` paths write the +/// whole `(bw+5)×(bh+5)` region before it is read, and `a`/`b` are written over +/// `bw*bh` samples by `luma_h`/`luma_v`/`luma_centre` before `pixel_avg`/`avg_full` +/// read the same range — so the zero-fill was dead in every case. +pub struct McScratch { + tile: [u8; LUMA_TILE * LUMA_TILE], + a: [u8; 256], + b: [u8; 256], +} + +/// Runs `f` with the thread's MC scratch borrowed ONCE. Callers that issue many +/// MC calls in a row (the bi-pred pair, the P-path rect ladder) hoist the +/// TLS lookup + RefCell borrow out of the per-call path by taking this at +/// region/MB scope and calling `mc_luma_padded_pre` inside — that fixed +/// per-call cost is paid twice per bi-pred region, ~1M sub-pel calls per clip. +#[inline] +pub fn with_mc_scratch(f: impl FnOnce(&mut McScratch) -> R) -> R { + MC_SCRATCH.with(|s| f(&mut s.borrow_mut())) +} + +thread_local! { + static MC_SCRATCH: core::cell::RefCell = const { + core::cell::RefCell::new(McScratch { + tile: [0; LUMA_TILE * LUMA_TILE], + a: [0; 256], + b: [0; 256], + }) + }; +} + +/// Dev-only census of `mc_luma` calls by block size × sub-pel phase. +/// +/// Exists to size the half-pel-plane-cache lever: with a cached plane set, a +/// half-pel call becomes a strided COPY and a quarter-pel call a 2-tap AVERAGE, +/// so the prize is (how many calls are sub-pel) × (filter cost − read cost). The +/// mix is deterministic, so this is valid on a loaded machine. +#[cfg(feature = "profile")] +pub mod mcstats { + use core::sync::atomic::{AtomicU64, Ordering}; + + /// Descent E depth-6: WHO calls `mc_luma`? `prof inter-mc` counts ~17 calls per + /// macroblock while reconstruction needs only 1-4, so the stage is dominated by + /// something other than recon and any prize computed against "recon MC" is priced + /// on the wrong population. Callers tag themselves; 0 = untagged. + pub const SITES: [&str; 5] = ["untagged", "recon", "search-fallback", "skip-check", "bdirect"]; + pub static SITE_COUNTS: [AtomicU64; 5] = [const { AtomicU64::new(0) }; 5]; + pub static SITE_CYCLES: [AtomicU64; 5] = [const { AtomicU64::new(0) }; 5]; + thread_local! { + pub static SITE: core::cell::Cell = const { core::cell::Cell::new(0) }; + } + /// Scoped tag: set on construction, restored on drop (call sites nest). + pub struct SiteTag(usize); + impl SiteTag { + pub fn new(s: usize) -> Self { + let prev = SITE.with(|c| c.replace(s)); + SiteTag(prev) + } + } + impl Drop for SiteTag { + fn drop(&mut self) { + SITE.with(|c| c.set(self.0)); + } + } + #[inline] + pub(super) fn site_add(c: u64) { + let s = SITE.with(|c| c.get()); + SITE_COUNTS[s].fetch_add(1, Ordering::Relaxed); + SITE_CYCLES[s].fetch_add(c, Ordering::Relaxed); + } + pub fn site_snapshot() -> Vec<(&'static str, u64, u64)> { + (0..5).map(|i| (SITES[i], SITE_COUNTS[i].load(Ordering::Relaxed), + SITE_CYCLES[i].load(Ordering::Relaxed))).collect() + } + + /// Phase classes: 0 = full-pel (0,0), 1 = half H/V, 2 = half centre (2,2), + /// 3 = quarter (one component odd). + pub const PHASES: [&str; 4] = ["fullpel", "half-HV", "half-ctr", "quarter"]; + /// Size classes: 16×16, 16×8/8×16, 8×8, 8×4/4×8, 4×4, other. + pub const SIZES: [&str; 6] = ["16x16", "16x8/8x16", "8x8", "8x4/4x8", "4x4", "other"]; + + pub static COUNTS: [AtomicU64; 24] = [const { AtomicU64::new(0) }; 24]; + /// Descent E depth-6: CYCLES per bucket. A call-count census is the WRONG + /// denominator for a prune — a full-pel 16x16 is a row copy, a quarter-pel is a + /// per-pixel 6-tap, and they differ ~10x. Weight by time, not by calls. + pub static CYCLES: [AtomicU64; 24] = [const { AtomicU64::new(0) }; 24]; + + #[inline] + pub(super) fn bucket(bw: usize, bh: usize, fx: i32, fy: i32) -> usize { + let size = match (bw, bh) { + (16, 16) => 0, + (16, 8) | (8, 16) => 1, + (8, 8) => 2, + (8, 4) | (4, 8) => 3, + (4, 4) => 4, + _ => 5, + }; + let phase = match (fx, fy) { + (0, 0) => 0, + (2, 2) => 2, + (fx, fy) if fx % 2 == 0 && fy % 2 == 0 => 1, + _ => 3, + }; + size * 4 + phase + } + + #[inline] + pub(super) fn add_cycles(b: usize, c: u64) { + CYCLES[b].fetch_add(c, Ordering::Relaxed); + } + + #[inline] + pub(super) fn record(bw: usize, bh: usize, fx: i32, fy: i32) { + let size = match (bw, bh) { + (16, 16) => 0, + (16, 8) | (8, 16) => 1, + (8, 8) => 2, + (8, 4) | (4, 8) => 3, + (4, 4) => 4, + _ => 5, + }; + let phase = match (fx, fy) { + (0, 0) => 0, + (2, 2) => 2, + (fx, fy) if fx % 2 == 0 && fy % 2 == 0 => 1, + _ => 3, + }; + COUNTS[size * 4 + phase].fetch_add(1, Ordering::Relaxed); + } + + pub fn reset() { + for c in COUNTS.iter() { + c.store(0, Ordering::Relaxed); + } + for c in CYCLES.iter() { + c.store(0, Ordering::Relaxed); + } + for c in SITE_COUNTS.iter() { + c.store(0, Ordering::Relaxed); + } + for c in SITE_CYCLES.iter() { + c.store(0, Ordering::Relaxed); + } + } + + /// `(size, phase, count, cycles)` for every non-empty bucket. + pub fn snapshot_cycles() -> Vec<(&'static str, &'static str, u64, u64)> { + let mut v = Vec::new(); + for i in 0..24 { + let n = COUNTS[i].load(Ordering::Relaxed); + if n != 0 { + v.push((SIZES[i / 4], PHASES[i % 4], n, CYCLES[i].load(Ordering::Relaxed))); + } + } + v + } + + /// `(size_label, phase_label, count)` for every non-empty bucket. + pub fn snapshot() -> Vec<(&'static str, &'static str, u64)> { + let mut v = Vec::new(); + for (i, c) in COUNTS.iter().enumerate() { + let n = c.load(Ordering::Relaxed); + if n > 0 { + v.push((SIZES[i / 4], PHASES[i % 4], n)); + } + } + v + } +} + +/// Extracts the `(bw+5)×(bh+5)` reference neighbourhood around the full-pel origin +/// `(ix0,iy0)` into `t`, clamping at the frame border — the edge-extended input +/// openh264's kernels assume. The block's top-left sample lands at tile `(2,2)`. +/// Returns the tile stride. Every sample in `[0, (bh+5)*ts)` is written. +fn luma_tile_into( + t: &mut [u8], + reference: &[u8], + cw: usize, + ch: usize, + ix0: isize, + iy0: isize, + bw: usize, + bh: usize, +) -> usize { + let ts = bw + 5; + // Interior fast path: the whole `(bw+5)×(bh+5)` halo is inside the frame, so no + // edge clamp is needed. Extract by contiguous row copies (a vectorized memcpy) + // — the unconditional per-pixel `clamp` on the slow path defeats + // autovectorization even when (as here) it would always be a no-op. + if ix0 - 2 >= 0 + && iy0 - 2 >= 0 + && ix0 - 2 + ts as isize <= cw as isize + && iy0 - 2 + (bh + 5) as isize <= ch as isize + && reference.len() >= cw * ch + { + let (rx0, ry0) = ((ix0 - 2) as usize, (iy0 - 2) as usize); + for ty in 0..bh + 5 { + let src = (ry0 + ty) * cw + rx0; + t[ty * ts..ty * ts + ts].copy_from_slice(&reference[src..src + ts]); + } + return ts; + } + for ty in 0..bh + 5 { + let ry = (iy0 - 2 + ty as isize).clamp(0, ch as isize - 1) as usize * cw; + for tx in 0..ts { + let rx = (ix0 - 2 + tx as isize).clamp(0, cw as isize - 1) as usize; + t[ty * ts + tx] = reference.get(ry + rx).copied().unwrap_or(0); + } + } + ts +} + +/// Horizontal half-pel plane (`McHorVer20`): `clip((6tapₕ + 16) >> 5)`, block +/// shifted by `(dr, dc)` tile rows/cols. +fn luma_h(t: &[u8], ts: usize, bw: usize, bh: usize, dr: usize, dc: usize, dst: &mut [u8]) { + #[cfg(accel)] + if bw == 16 || bw == 8 { + rusty_h264_accel::mc_hor20(t, (2 + dr) * ts + 2 + dc, ts, dst, bw, bh); + return; + } + for r in 0..bh { + let base = (2 + r + dr) * ts + 2 + dc; + for c in 0..bw { + let p = base + c; + let f = t[p - 2] as i32 - 5 * t[p - 1] as i32 + 20 * t[p] as i32 + 20 * t[p + 1] as i32 + - 5 * t[p + 2] as i32 + + t[p + 3] as i32; + dst[r * bw + c] = clip_u8((f + 16) >> 5) as u8; + } + } +} + +/// Vertical half-pel plane (`McHorVer02`): `clip((6tapᵥ + 16) >> 5)`. +fn luma_v(t: &[u8], ts: usize, bw: usize, bh: usize, dr: usize, dc: usize, dst: &mut [u8]) { + #[cfg(accel)] + if bw == 16 || bw == 8 { + rusty_h264_accel::mc_ver02(t, (2 + dr) * ts + 2 + dc, ts, dst, bw, bh); + return; + } + for r in 0..bh { + let base = (2 + r + dr) * ts + 2 + dc; + for c in 0..bw { + let p = base + c; + let f = t[p - 2 * ts] as i32 - 5 * t[p - ts] as i32 + 20 * t[p] as i32 + + 20 * t[p + ts] as i32 + - 5 * t[p + 2 * ts] as i32 + + t[p + 3 * ts] as i32; + dst[r * bw + c] = clip_u8((f + 16) >> 5) as u8; + } + } +} + +/// Centre half-pel plane (`McHorVer22`): vertical 6-tap to 16-bit intermediates, +/// then horizontal 6-tap — `clip((·+ 512) >> 10)`. +fn luma_centre(t: &[u8], ts: usize, bw: usize, bh: usize, dst: &mut [u8]) { + #[cfg(accel)] + if bw == 16 || bw == 8 { + rusty_h264_accel::mc_centre(t, ts, dst, bw, bh); + return; + } + let mut itmp = [0i32; LUMA_TILE]; + for r in 0..bh { + let base = (2 + r) * ts; + for (j, slot) in itmp[..bw + 5].iter_mut().enumerate() { + let p = base + j; + *slot = t[p - 2 * ts] as i32 - 5 * t[p - ts] as i32 + 20 * t[p] as i32 + + 20 * t[p + ts] as i32 + - 5 * t[p + 2 * ts] as i32 + + t[p + 3 * ts] as i32; + } + for c in 0..bw { + let f = itmp[c] - 5 * itmp[c + 1] + 20 * itmp[c + 2] + 20 * itmp[c + 3] - 5 * itmp[c + 4] + + itmp[c + 5]; + dst[r * bw + c] = clip_u8((f + 512) >> 10) as u8; + } + } +} + +/// `PixelAvg_c`: `(a + b + 1) >> 1` of two clipped planes. +fn pixel_avg(a: &[u8], b: &[u8], bw: usize, bh: usize, dst: &mut [u8]) { + let n = bw * bh; + // Same leak `avg_full` fixed, for the TWO-FILTER quarter positions + // ((1,1)/(3,1)/(1,3)/(3,3) and the centre-adjacent four): the average on + // top of the asm half-pel kernels was a scalar runtime-width loop. The MC + // census prices quarter-pel at ~68% of decoder MC cycles, and the eight + // positions served here all end in this loop. `pavgb` computes + // `(a + b + 1) >> 1` exactly — byte-identical. The scalar loop stays as + // the non-accel path and the oracle. + // + // The TRUE block geometry is passed, never reconstructed from `n`: the + // openh264 row loops are unrolled by more than one row, so a synthetic + // (16, n/16) shape with h < 4 over-runs the block — that was a real + // SEGFAULT on every sub-8x8 stream (first cut of this dispatch, caught by + // the corpus gate). The kernels are exercised at every real (bw, bh ≥ 4) + // shape by `avg_full` already. + #[cfg(accel)] + if (bw == 16 || bw == 8 || bw == 4) && a.len() >= n && b.len() >= n && dst.len() >= n { + rusty_h264_accel::pixel_avg(&mut dst[..n], &a[..n], bw, &b[..n], bw, bw, bh); + return; + } + for i in 0..n { + dst[i] = ((a[i] as i32 + b[i] as i32 + 1) >> 1) as u8; + } +} + +/// `PixelAvg_c` of a half-pel plane with a full-pel block shifted by `(dr, dc)`. +fn avg_full(t: &[u8], ts: usize, bw: usize, bh: usize, dr: usize, dc: usize, half: &[u8], dst: &mut [u8]) { + // The QUARTER-PEL step. `luma_h`/`luma_v`/`luma_centre` have been on asm for a + // long time; this average layered on top of them stayed a scalar per-pixel loop + // with a runtime width. On real x264 streams ~85% of decoder MC cycles are + // quarter-pel, so this loop was handing the kernel's win back on the large + // majority of MC. `pavgb` computes `(a + b + 1) >> 1` exactly — byte-identical. + #[cfg(accel)] + if bw == 16 || bw == 8 || bw == 4 { + let base = (2 + dr) * ts + 2 + dc; + rusty_h264_accel::pixel_avg(dst, &t[base..], ts, half, bw, bw, bh); + return; + } + for r in 0..bh { + let base = (2 + r + dr) * ts + 2 + dc; + for c in 0..bw { + dst[r * bw + c] = ((t[base + c] as i32 + half[r * bw + c] as i32 + 1) >> 1) as u8; + } + } +} + +/// A/B: restore half→scratch→avg compose for one-filter qpel (`RS_H264_QPEL_COMPOSE=1`). +#[inline] +fn qpel_compose() -> bool { + use std::sync::OnceLock; + static V: OnceLock = OnceLock::new(); + *V.get_or_init(|| std::env::var_os("RS_H264_QPEL_COMPOSE").is_some_and(|v| v == "1")) +} + +/// One-filter qpel (`(1,0)/(3,0)/(0,1)/(0,3)`): fused half+avg when accel + w∈{8,16}. +/// `horiz`: horizontal 6-tap; else vertical. `fshift`: full-pel offset (0 or 1) in the +/// filter axis (`fdc` for horiz, `fdr` for vert) — matches `avg_full`'s (0,1)/(1,0). +fn qpel_one_filter( + t: &[u8], + ts: usize, + bw: usize, + bh: usize, + horiz: bool, + fshift: usize, + out: &mut [u8], +) { + #[cfg(accel)] + if !qpel_compose() && (bw == 16 || bw == 8) { + let off = 2 * ts + 2; + if horiz { + rusty_h264_accel::mc_hor_qpel(t, off, ts, out, bw, bh, fshift); + } else { + rusty_h264_accel::mc_ver_qpel(t, off, ts, out, bw, bh, fshift); + } + return; + } + // Compose oracle / narrow widths / non-accel: half into a stack scratch, then avg. + let mut half = [0u8; 256]; + let n = bw * bh; + debug_assert!(n <= 256); + if horiz { + luma_h(t, ts, bw, bh, 0, 0, &mut half[..n]); + avg_full(t, ts, bw, bh, 0, fshift, &half[..n], out); + } else { + luma_v(t, ts, bw, bh, 0, 0, &mut half[..n]); + avg_full(t, ts, bw, bh, fshift, 0, &half[..n], out); + } +} + +/// Two-filter HV qpel: horizontal half into `a`, then vertical half+avg into `out` +/// (kills the second scratch store). Compose oracle when `qpel_compose()`. +fn qpel_hv( + t: &[u8], + ts: usize, + bw: usize, + bh: usize, + hdr: usize, + hdc: usize, + vdr: usize, + vdc: usize, + a: &mut [u8], + out: &mut [u8], +) { + luma_h(t, ts, bw, bh, hdr, hdc, a); + #[cfg(accel)] + if !qpel_compose() && (bw == 16 || bw == 8) { + let off = (2 + vdr) * ts + 2 + vdc; + rusty_h264_accel::mc_ver02_avg(t, off, ts, out, bw, bh, a, bw); + return; + } + let n = bw * bh; + let mut b = [0u8; 256]; + debug_assert!(n <= 256); + luma_v(t, ts, bw, bh, vdr, vdc, &mut b[..n]); + pixel_avg(a, &b[..n], bw, bh, out); +} + +/// The `McLuma_c` `[mvx&3][mvy&3]` dispatch over the clamped tile (sub-pel only; +/// `(0,0)` is handled by the full-pel copy path in [`mc_luma`]). +#[allow(clippy::too_many_arguments)] +fn mc_luma_subpel( + t: &[u8], + ts: usize, + bw: usize, + bh: usize, + fx: i32, + fy: i32, + a: &mut [u8], + b: &mut [u8], + out: &mut [u8], +) { + // `a`/`b` are caller-owned scratch (see `McScratch`): every arm below fully + // writes the `n` samples it later reads, so their prior contents are dead. + // One-filter qpel no longer needs them when fused (see `qpel_one_filter`). + match (fx, fy) { + (2, 0) => luma_h(t, ts, bw, bh, 0, 0, out), + (0, 2) => luma_v(t, ts, bw, bh, 0, 0, out), + (2, 2) => luma_centre(t, ts, bw, bh, out), + // One-filter qpel: fuse half-pel + pavgb (openh264 McHorVer10/30/01/03). + // Compose path (`RS_H264_QPEL_COMPOSE=1`) keeps the scratch store as A/B oracle. + (1, 0) => qpel_one_filter(t, ts, bw, bh, true, 0, out), + (3, 0) => qpel_one_filter(t, ts, bw, bh, true, 1, out), + (0, 1) => qpel_one_filter(t, ts, bw, bh, false, 0, out), + (0, 3) => qpel_one_filter(t, ts, bw, bh, false, 1, out), + (1, 1) => qpel_hv(t, ts, bw, bh, 0, 0, 0, 0, a, out), + (3, 1) => qpel_hv(t, ts, bw, bh, 0, 0, 0, 1, a, out), + (1, 3) => qpel_hv(t, ts, bw, bh, 1, 0, 0, 0, a, out), + (3, 3) => qpel_hv(t, ts, bw, bh, 1, 0, 0, 1, a, out), + (2, 1) => { + luma_h(t, ts, bw, bh, 0, 0, a); + luma_centre(t, ts, bw, bh, b); + pixel_avg(a, b, bw, bh, out); + } + (2, 3) => { + luma_h(t, ts, bw, bh, 1, 0, a); + luma_centre(t, ts, bw, bh, b); + pixel_avg(a, b, bw, bh, out); + } + (1, 2) => { + luma_v(t, ts, bw, bh, 0, 0, a); + luma_centre(t, ts, bw, bh, b); + pixel_avg(a, b, bw, bh, out); + } + (3, 2) => { + luma_v(t, ts, bw, bh, 0, 1, a); + luma_centre(t, ts, bw, bh, b); + pixel_avg(a, b, bw, bh, out); + } + _ => unreachable!("(0,0) is the full-pel path"), + } +} + +/// The three half-pel luma planes of one reference picture, at full frame size. +/// +/// x264 filters these ONCE per reference frame and then every sub-pel motion-search +/// candidate is a strided copy from one plane (half positions) or a 2-tap average of +/// two (quarter positions). We previously re-ran the 6-tap per candidate: measured at +/// 166 s of a 266 s quality-preset encode over 991 M calls, against x264's 188 ms of +/// `hpel-filter` for the entire corpus. +/// +/// Naming follows the spec's sample grid at full-pel `G`: +/// `h` = `b` (half-pel horizontal) · `v` = `h` (half-pel vertical) · `c` = `j` (centre) +#[derive(Clone, Debug)] +pub struct HpelPlanes { + /// Edge-replicated FULL-pel plane. Needed as an operand for the quarter + /// positions that average against `G`, and padded so out-of-frame candidates + /// resolve without a bounds decline. + pub f: Vec, + pub h: Vec, + pub v: Vec, + pub c: Vec, + /// Row stride of every plane (`cw + 2*HPEL_PAD`). + pub stride: usize, + pub pad: usize, + pub pw: usize, + pub ph: usize, + pub cw: usize, + pub ch: usize, +} + +/// Border added to every cached plane, in samples. +/// +/// Sized so a ±24 motion search around any macroblock still lands inside: a 16-wide +/// block at the right edge reaches `cw + 24`, and reading its `+1` neighbour needs +/// `cw + 41` ≤ `cw + PAD`. Without a border the plane cache DECLINED every candidate +/// whose vector left the picture — 62.5% of the remaining `mc_luma` fallbacks, at +/// ~195 ns against 33 ns for a plane read. +/// +/// SWEPT (foreman / bus / park_joy, `RFF_HPEL_PAD`), because a bigger border is a +/// TRADE — more candidates covered, but a larger working set (4 planes over +/// `(cw+2P)(ch+2P)`) and a costlier per-frame build: +/// +/// | pad | foreman fallbacks | bus | park_joy | build (foreman) | +/// |---|---|---|---|---| +/// | 0 | 207,537 | 838,581 | 6,354,258 | 5.7 ms | +/// | 8 | 127,407 | 774,592 | 6,172,777 | 4.8 ms | +/// | **16** | **127,274** | **765,625** | **6,122,122** | **6.1 ms** | +/// | 32 | 127,262 | 764,999 | 6,093,358 | 9.0 ms | +/// +/// Padding replicated around each cached half-pel plane. +/// +/// 32, raised from 16 after the edge full-pel path landed. The earlier sweep found the +/// pad made NO difference and was correctly recorded as refuted -- but that measurement +/// ran against a population dominated by FULL-PEL declines, which `hpel_ref` now serves. +/// The refutation expired when its baseline moved. Re-swept, pad 32 removes essentially +/// every remaining search fallback (football 17,662 -> 175, foreman 3,238 -> 0). +/// +/// Priced at the PIPELINE level, not by component arithmetic -- the component estimate +/// was wrong in both directions (it mixed an rdtsc cycle census with profiler +/// milliseconds via an assumed clock, and read a 23-sample build cost off single runs). +/// Paired ABBA, median of paired ratios: bus 1.113x (14/14), blue_sky 1.054x (6/6), +/// park_joy 1.050x (11/12), football 1.026x (11/14), foreman 1.015x (ns), +/// crowd_run 1.005x (ns). No clip regresses; the gain tracks edge-overhang density, so +/// fast pans benefit most and large frames least. +/// +/// Byte-identical at 16/32/64 -- a wider pad grows the planes but never changes a value +/// read. `RFF_HPEL_PAD` overrides. +pub const HPEL_PAD_DEFAULT: usize = 32; +pub fn hpel_pad() -> usize { + use std::sync::OnceLock; + static P: OnceLock = OnceLock::new(); + *P.get_or_init(|| { + std::env::var("RFF_HPEL_PAD") + .ok() + .and_then(|s| s.parse().ok()) + .unwrap_or(HPEL_PAD_DEFAULT) + .clamp(0, 128) + }) +} + +/// Builds the three half-pel planes for `reference` (`cw`×`ch`, MB-aligned). +/// +/// Bit-exact with [`mc_luma`] by CONSTRUCTION: it walks the frame in the same 16×16 +/// blocks, extracts the same clamped halo via [`luma_tile_into`], and runs the same +/// `luma_h`/`luma_v`/`luma_centre` kernels. Each output sample depends only on the +/// six clamped input samples around it, so the value is independent of which block +/// computed it. +/// Edge-replicates a `w`×`h` plane into a `(w+2·pad)`×`(h+2·pad)` padded copy — +/// openh264's `ExpandPicture`. `mc_luma` clamps each tap independently via `at()`, +/// and clamping IS edge replication, so filtering the padded plane is bit-identical +/// to the clamped-read original (the argument `build_hpel_planes` rests on; the +/// decoder's per-reference padding reuses it so per-MC-call tile extraction dies). +pub fn pad_plane(src: &[u8], w: usize, h: usize, pad: usize) -> Vec { + pad_plane_into(Vec::new(), src, w, h, pad) +} + +/// `pad_plane` reusing a recycled buffer. Every byte of the padded plane is +/// written by the row loop below (left fill + interior copy + right fill, all +/// `ph` rows), so a RIGHT-SIZED recycled buffer needs no clearing at all — and, +/// unlike a fresh `vec![0; n]` (whose zero pages are free but whose first +/// touches page-fault), its pages are already mapped and warm. This is what the +/// earlier pad_plane memset-elimination attempt (refuted, WHYS ledger) was +/// missing: on a FRESH alloc the memset is free; the win only exists when the +/// allocation itself is recycled. +pub fn pad_plane_into(mut f: Vec, src: &[u8], w: usize, h: usize, pad: usize) -> Vec { + let (pw, ph) = (w + 2 * pad, h + 2 * pad); + if f.len() != pw * ph { + f.clear(); + f.resize(pw * ph, 0); + } + for y in 0..ph { + let sy = (y as isize - pad as isize).clamp(0, h as isize - 1) as usize; + let row = &src[sy * w..sy * w + w]; + let d = &mut f[y * pw..y * pw + pw]; + d[..pad].fill(row[0]); + d[pad..pad + w].copy_from_slice(row); + d[pad + w..].fill(row[w - 1]); + } + f +} + +pub fn build_hpel_planes(reference: &[u8], cw: usize, ch: usize) -> HpelPlanes { + let _g = crate::prof::scope(crate::prof::Stage::MeHpelBuild); + let pad = hpel_pad(); + let (pw, ph) = (cw + 2 * pad, ch + 2 * pad); + // 1. Edge-replicated source (see `pad_plane` for why this is bit-identical). + let f = pad_plane(reference, cw, ch, pad); + // 2. Filter the three half-pel planes over the padded area. + let mut h = vec![0u8; pw * ph]; + let mut v = vec![0u8; pw * ph]; + let mut c = vec![0u8; pw * ph]; + // Dispatch ladder: the AVX2 FUSED single pass (side-by-side descent: the tile + // walk measured 8× x264's hpel-filter, whose fused shape this kernel mirrors) + // → env-forced scalar fused (RFF_HPEL_FUSED=1, the oracle base) → tile walk. + // All three are byte-identical (`fused_hpel_builder_matches_tiles`, + // `avx2_fused_matches_scalar_fused`); the choice is speed only. + #[cfg(accel)] + let done = !hpel_fused_forced_off() && rusty_h264_accel::hpel_fused(&f, pw, ph, &mut h, &mut v, &mut c); + #[cfg(not(accel))] + let done = false; + if !done { + if hpel_fused_enabled() { + build_hpel_fused(&f, pw, ph, &mut h, &mut v, &mut c); + } else { + build_hpel_tiles(&f, pw, ph, &mut h, &mut v, &mut c); + } + } + HpelPlanes { f, h, v, c, stride: pw, pad, pw, ph, cw, ch } +} + +/// Campaign-3 knob. DEFAULT OFF (the tile walk): the scalar fused pass measured +/// SLOWER than the tile walk (950 vs 617 µs/frame CIF) because the tiles run the +/// SSE2/AVX2 `mc_hor20/ver02/centre` asm kernels — their throughput beats the +/// fused pass's redundancy savings. The fused builder + its byte-identity oracle +/// stay in-tree as the base for a future AVX2 fused kernel (`RFF_HPEL_FUSED=1`), +/// which is the only shape that can beat the tiles. +fn hpel_fused_enabled() -> bool { + use std::sync::OnceLock; + static E: OnceLock = OnceLock::new(); + *E.get_or_init(|| std::env::var("RFF_HPEL_FUSED").map(|s| s == "1").unwrap_or(false)) +} + +/// `RFF_HPEL_AVX2=0` pins the pre-kernel path (tile walk / scalar fused) for A/B — +/// the AVX2 fused pass is byte-identical, so this is a speed-experiment knob only. +#[cfg(accel)] +fn hpel_fused_forced_off() -> bool { + use std::sync::OnceLock; + static E: OnceLock = OnceLock::new(); + *E.get_or_init(|| std::env::var("RFF_HPEL_AVX2").map(|s| s == "0").unwrap_or(false)) +} + +/// The ORIGINAL builder — walks 16×16 tiles through `luma_tile_into` + the MC +/// kernels. Kept as the fused builder's oracle and the `RFF_HPEL_FUSED=0` path. +fn build_hpel_tiles(f: &[u8], pw: usize, ph: usize, h: &mut [u8], v: &mut [u8], c: &mut [u8]) { + let mut tile = [0u8; LUMA_TILE * LUMA_TILE]; + let mut blk = [0u8; 256]; + let mut by = 0; + while by < ph { + let mut bx = 0; + while bx < pw { + let bh = 16.min(ph - by); + let bwid = 16.min(pw - bx); + let ts = luma_tile_into(&mut tile, f, pw, ph, bx as isize, by as isize, bwid, bh); + for kind in 0u8..3 { + let plane: &mut [u8] = match kind { + 0 => &mut *h, + 1 => &mut *v, + _ => &mut *c, + }; + match kind { + 0 => luma_h(&tile, ts, bwid, bh, 0, 0, &mut blk), + 1 => luma_v(&tile, ts, bwid, bh, 0, 0, &mut blk), + _ => luma_centre(&tile, ts, bwid, bh, &mut blk), + } + for r in 0..bh { + plane[(by + r) * pw + bx..][..bwid].copy_from_slice(&blk[r * bwid..][..bwid]); + } + } + bx += 16; + } + by += 16; + } +} + +/// Campaign 3 (lets-win-optimize.md): the FUSED single-pass builder — x264's +/// `hpel_filter` shape. The tile walk re-extracts a `(16+5)²` halo per 16×16 block +/// (1.7× redundant reads), re-runs per-tile dispatch, and copies each block out +/// three times; this pass reads each source row band once and writes H, V, C +/// directly. BYTE-IDENTICAL to the tile builder: the same 6-tap integer formulas +/// over the same clamped `f` samples (interior rows/cols never clamp; the ±2/3 +/// borders of the padded plane clamp exactly like `luma_tile_into`'s halo does), +/// and the centre's i32 vertical intermediates reproduce `luma_centre`'s order. +/// Pinned by `fused_hpel_builder_matches_tiles`. +fn build_hpel_fused(f: &[u8], pw: usize, ph: usize, h: &mut [u8], v: &mut [u8], c: &mut [u8]) { + let cl = |i: isize, hi: usize| i.clamp(0, hi as isize - 1) as usize; + // Extended per-row buffers: index j covers column j-2 (clamped into the plane). + let mut vt = vec![0i32; pw + 5]; // vertical 6-tap intermediates (unrounded) + let mut hb = vec![0u8; pw + 5]; // this row's source with clamped column halo + for y in 0..ph { + let (ym2, ym1, y0, yp1, yp2, yp3) = ( + cl(y as isize - 2, ph) * pw, + cl(y as isize - 1, ph) * pw, + y * pw, + cl(y as isize + 1, ph) * pw, + cl(y as isize + 2, ph) * pw, + cl(y as isize + 3, ph) * pw, + ); + // Column-clamped borders (≤5 samples each side); the interior runs with + // DIRECT indices — a per-element clamp in this loop defeats + // autovectorization and measured the whole builder 2.2× slower. + for j in 0..2 { + let x = 0usize; + vt[j] = f[ym2 + x] as i32 - 5 * f[ym1 + x] as i32 + 20 * f[y0 + x] as i32 + + 20 * f[yp1 + x] as i32 + - 5 * f[yp2 + x] as i32 + + f[yp3 + x] as i32; + hb[j] = f[y0 + x]; + } + for j in 2..pw + 2 { + let x = j - 2; + vt[j] = f[ym2 + x] as i32 - 5 * f[ym1 + x] as i32 + 20 * f[y0 + x] as i32 + + 20 * f[yp1 + x] as i32 + - 5 * f[yp2 + x] as i32 + + f[yp3 + x] as i32; + hb[j] = f[y0 + x]; + } + for j in pw + 2..pw + 5 { + let x = pw - 1; + vt[j] = f[ym2 + x] as i32 - 5 * f[ym1 + x] as i32 + 20 * f[y0 + x] as i32 + + 20 * f[yp1 + x] as i32 + - 5 * f[yp2 + x] as i32 + + f[yp3 + x] as i32; + hb[j] = f[y0 + x]; + } + let hrow = &mut h[y0..y0 + pw]; + let vrow = &mut v[y0..y0 + pw]; + let crow = &mut c[y0..y0 + pw]; + for x in 0..pw { + vrow[x] = clip_u8((vt[x + 2] + 16) >> 5) as u8; + } + for x in 0..pw { + let s = vt[x] - 5 * vt[x + 1] + 20 * vt[x + 2] + 20 * vt[x + 3] - 5 * vt[x + 4] + + vt[x + 5]; + crow[x] = clip_u8((s + 512) >> 10) as u8; + } + for x in 0..pw { + let s = hb[x] as i32 - 5 * hb[x + 1] as i32 + 20 * hb[x + 2] as i32 + + 20 * hb[x + 3] as i32 + - 5 * hb[x + 4] as i32 + + hb[x + 5] as i32; + hrow[x] = clip_u8((s + 16) >> 5) as u8; + } + } +} + +/// Fills `out` with the `bw`×`bh` sub-pel prediction read from cached planes. +/// +/// Returns `false` when the access (which may reach one sample past the block on +/// either axis, for the `m`/`s` neighbours) is not fully interior — the caller then +/// falls back to [`mc_luma`]. Bit-identical to `mc_luma` wherever it returns `true`: +/// each arm below is the same pair of operands `mc_luma_subpel` averages. +#[allow(clippy::too_many_arguments)] +/// Descent C: half-pel (single-plane, copy-free-able) vs quarter-pel (two-plane average). +#[cfg(feature = "profile")] +pub mod hpelphase { + use core::sync::atomic::{AtomicU64, Ordering}; + pub static C: [AtomicU64; 2] = [const { AtomicU64::new(0) }; 2]; + #[inline] + pub fn bump(i: usize) { C[i].fetch_add(1, Ordering::Relaxed); } + pub fn reset() { for c in C.iter() { c.store(0, Ordering::Relaxed); } } + pub fn snapshot() -> Vec { C.iter().map(|c| c.load(Ordering::Relaxed)).collect() } +} + +/// Descent C: the SINGLE-PLANE (half-pel) phases — (2,0)->h, (0,2)->v, (2,2)->c — +/// are already contiguous at plane stride, exactly like the interior full-pel case. +/// Hand the consumer `(plane, base, stride)` so it can read them IN PLACE rather than +/// copy 256 bytes into a temp first. Byte-identical to `hpel_block` by construction: +/// same plane, same base, same samples — only the copy is elided. +/// Returns `None` for quarter-pel (a two-plane average, which must be materialized), +/// for out-of-range coordinates, and whenever `hpel_block` would decline. +#[inline] +pub fn hpel_ref<'a>( + p: &'a HpelPlanes, + x0: usize, + y0: usize, + bw: usize, + bh: usize, + mvx: i32, + mvy: i32, +) -> Option<(&'a [u8], usize, usize)> { + let (fx, fy) = (mvx & 3, mvy & 3); + let plane = match (fx, fy) { + (2, 0) => &p.h, + (0, 2) => &p.v, + (2, 2) => &p.c, + // Descent E: FULL-PEL off the frame edge. `hpel_block` declines these before its + // bounds check ("the full-pel copy path is already optimal"), so the caller fell + // back to a per-pixel clamped `mc_luma` -- measured at 76-79% of all mc_luma + // TIME, the single largest consumer of that stage. But `f` IS the padded, + // edge-replicated reference, so it reproduces mc_luma's clamp exactly and can be + // read in place like any other phase. (Widening the pad does NOT fix this: the + // decline count is identical at pad 16 and pad 64 -- it was never a bounds issue.) + (0, 0) => &p.f, + _ => return None, + }; + let (ix0, iy0) = (x0 as isize + (mvx >> 2) as isize, y0 as isize + (mvy >> 2) as isize); + let (px, py) = (ix0 + p.pad as isize, iy0 + p.pad as isize); + // Identical guard to `hpel_block`, including its `+1` slack, so the two paths + // accept exactly the same candidate set (no bitstream drift from a wider path). + if px < 0 || py < 0 || px + bw as isize + 1 > p.pw as isize || py + bh as isize + 1 > p.ph as isize { + return None; + } + let base = py as usize * p.stride + px as usize; + if base + (bh - 1) * p.stride + bw > plane.len() { + return None; + } + Some((plane, base, p.stride)) +} + +/// Challenge-1 A3: the QUARTER-pel companion of [`hpel_ref`] — resolves the two +/// plane operands whose `(a+b+1)>>1` average IS the prediction, so the ME cost can +/// be one fused avg+SATD kernel pass instead of materialize-256-bytes-then-SATD. +/// Same bounds guard as [`hpel_block`] (identical accepted-candidate set); returns +/// `(plane_a, base_a, plane_b, base_b, stride)`. `None` for non-quarter phases +/// (those are [`hpel_ref`]'s) and whenever `hpel_block` would decline. +#[inline] +pub fn hpel_qpel_refs<'a>( + p: &'a HpelPlanes, + x0: usize, + y0: usize, + bw: usize, + bh: usize, + mvx: i32, + mvy: i32, +) -> Option<(&'a [u8], usize, &'a [u8], usize, usize)> { + let (fx, fy) = (mvx & 3, mvy & 3); + // Quarter phases only: at least one fractional part is odd. + if fx & 1 == 0 && fy & 1 == 0 { + return None; + } + let (ix0, iy0) = (x0 as isize + (mvx >> 2) as isize, y0 as isize + (mvy >> 2) as isize); + let (px, py) = (ix0 + p.pad as isize, iy0 + p.pad as isize); + if px < 0 || py < 0 || px + bw as isize + 1 > p.pw as isize || py + bh as isize + 1 > p.ph as isize { + return None; + } + let stride = p.stride; + let base = py as usize * stride + px as usize; + let g: &[u8] = &p.f; + // The SAME operand table as `hpel_block`'s quarter arm (the spec's `m`/`s` + // neighbour shifts baked into the base offsets). + let (pa, oa, pb, ob): (&[u8], usize, &[u8], usize) = match (fx, fy) { + (1, 0) => (g, 0, &p.h, 0), + (3, 0) => (g, 1, &p.h, 0), + (0, 1) => (g, 0, &p.v, 0), + (0, 3) => (g, stride, &p.v, 0), + (1, 1) => (&p.h, 0, &p.v, 0), + (3, 1) => (&p.h, 0, &p.v, 1), + (1, 3) => (&p.h, stride, &p.v, 0), + (3, 3) => (&p.h, stride, &p.v, 1), + (2, 1) => (&p.h, 0, &p.c, 0), + (2, 3) => (&p.h, stride, &p.c, 0), + (1, 2) => (&p.v, 0, &p.c, 0), + _ => (&p.v, 1, &p.c, 0), // (3, 2) + }; + // Slice-length check so a short plane can never OOB (the `+1` slack in the + // bounds test above covers the shifted operand's reach geometrically; this + // makes it a hard guarantee at the slice level too). + if base + oa + (bh - 1) * stride + bw > pa.len() || base + ob + (bh - 1) * stride + bw > pb.len() { + return None; + } + Some((pa, base + oa, pb, base + ob, stride)) +} + +pub fn hpel_block( + p: &HpelPlanes, + x0: usize, + y0: usize, + bw: usize, + bh: usize, + mvx: i32, + mvy: i32, + out: &mut [u8], +) -> bool { + let _g = crate::prof::scope(crate::prof::Stage::MeHpel); + let (ix0, iy0) = (x0 as isize + (mvx >> 2) as isize, y0 as isize + (mvy >> 2) as isize); + let (fx, fy) = (mvx & 3, mvy & 3); + if fx == 0 && fy == 0 { + return false; // the full-pel copy path is already optimal + } + // Padded coordinates. The `+1` slack covers the `m`/`s` neighbours. + let (px, py) = (ix0 + p.pad as isize, iy0 + p.pad as isize); + if px < 0 || py < 0 || px + bw as isize + 1 > p.pw as isize || py + bh as isize + 1 > p.ph as isize { + return false; + } + let stride = p.stride; + let base = py as usize * stride + px as usize; + + let single = match (fx, fy) { + (2, 0) => Some(&p.h), + (0, 2) => Some(&p.v), + (2, 2) => Some(&p.c), + _ => None, + }; + // Descent C: single-plane (half-pel) reads are CONTIGUOUS AT PLANE STRIDE — they + // could be SATD'd in place like the interior full-pel path instead of copied into + // a temp. Count the split before building that path. + #[cfg(feature = "profile")] + crate::inter::hpelphase::bump(if single.is_some() { 0 } else { 1 }); + if let Some(src) = single { + for r in 0..bh { + out[r * bw..r * bw + bw].copy_from_slice(&src[base + r * stride..][..bw]); + } + return true; + } + + // Quarter-pel: (a + b + 1) >> 1 of two planes. The operand table (the spec's + // `m`/`s` neighbour shifts) lives in ONE place — `hpel_qpel_refs` — so the + // materializing path here and the fused avg+SATD path can never drift apart. + let Some((pa, ba, pb, bb, qstride)) = hpel_qpel_refs(p, x0, y0, bw, bh, mvx, mvy) else { + return false; + }; + match bw { + 16 => avg_rows::<16>(pa, ba, pb, bb, qstride, bh, out), + 8 => avg_rows::<8>(pa, ba, pb, bb, qstride, bh, out), + 4 => avg_rows::<4>(pa, ba, pb, bb, qstride, bh, out), + _ => return false, + } + true +} + +#[inline] +fn avg_rows(pa: &[u8], oa: usize, pb: &[u8], ob: usize, cw: usize, bh: usize, out: &mut [u8]) { + for r in 0..bh { + let sa = &pa[oa + r * cw..][..BW]; + let sb = &pb[ob + r * cw..][..BW]; + let o = &mut out[r * BW..r * BW + BW]; + for i in 0..BW { + o[i] = ((sa[i] as u16 + sb[i] as u16 + 1) >> 1) as u8; + } + } +} + +/// Quarter-pel motion compensation of a `bw`×`bh` luma block (`McLuma_c`). +#[allow(clippy::too_many_arguments)] +/// Descent E: accumulates one `mc_luma` call's cycles into its (size, phase) bucket. +#[cfg(feature = "profile")] +struct McCycleGuard { + b: usize, + t: u64, +} +#[cfg(feature = "profile")] +impl Drop for McCycleGuard { + fn drop(&mut self) { + let c = crate::prof::tick().wrapping_sub(self.t); + mcstats::add_cycles(self.b, c); + mcstats::site_add(c); + } +} + +pub fn mc_luma( + reference: &[u8], + cw: usize, + ch: usize, + x0: usize, + y0: usize, + bw: usize, + bh: usize, + mvx: i32, + mvy: i32, + out: &mut [u8], +) { + let _g = crate::prof::scope(crate::prof::Stage::InterMc); + if abl_mc() { + out.fill(128); + return; + } + let (ix0, iy0) = (x0 as isize + (mvx >> 2) as isize, y0 as isize + (mvy >> 2) as isize); + let (fx, fy) = (mvx & 3, mvy & 3); + #[cfg(feature = "profile")] + mcstats::record(bw, bh, fx, fy); + // Descent E: time this call into its (size, phase) bucket. Guard drops at fn end. + #[cfg(feature = "profile")] + let _mcg = McCycleGuard { b: mcstats::bucket(bw, bh, fx, fy), t: crate::prof::tick() }; + if fx == 0 && fy == 0 { + // Full-pel: a verbatim copy of the reference (`McCopy_c`). Interior → a + // row-wise slice copy (auto-vectorized); edge → per-pixel clamped. + if ix0 >= 0 + && iy0 >= 0 + && ix0 + bw as isize <= cw as isize + && iy0 + bh as isize <= ch as isize + && reference.len() >= cw * ch + { + let (rx, ry) = (ix0 as usize, iy0 as usize); + // Fixed-size fast path for the full 16×16 MB (the overwhelming common + // case). With `bw` a runtime parameter each `copy_from_slice(..bw)` is a + // variable-length `memcpy` CALL per row (~38 ns / MB); const-16 slices + // let LLVM emit inline 16-byte moves (~2 ns / MB). Byte-identical. + if bw == 16 && bh == 16 { + for dy in 0..16 { + let s = &reference[(ry + dy) * cw + rx..]; + out[dy * 16..dy * 16 + 16].copy_from_slice(&s[..16]); + } + } else { + for dy in 0..bh { + out[dy * bw..dy * bw + bw] + .copy_from_slice(&reference[(ry + dy) * cw + rx..][..bw]); + } + } + } else { + for dy in 0..bh { + for dx in 0..bw { + out[dy * bw + dx] = + at(reference, cw, ch, ix0 + dx as isize, iy0 + dy as isize) as u8; + } + } + } + return; + } + // Sub-pel: extract the clamped tile once, then run the openh264 block kernels. + // Tile + half-pel staging live in per-thread scratch (see `McScratch`) so the + // ~1.4 KB of zero-fill and the tile's return-by-value copy are not repaid on + // every motion-search candidate. Destructuring gives `tile` and `a`/`b` as + // disjoint borrows of the same scratch. + MC_SCRATCH.with(|s| { + let McScratch { tile, a, b } = &mut *s.borrow_mut(); + let ts = luma_tile_into(tile, reference, cw, ch, ix0, iy0, bw, bh); + mc_luma_subpel(tile, ts, bw, bh, fx, fy, a, b, out); + }); +} + +/// Eighth-pel bilinear motion compensation of a `bw`×`bh` chroma block (spec +/// §8.4.2.2.2). The chroma motion vector equals the luma MV; for 4:2:0 it is +/// interpreted at eighth-chroma-sample resolution. +#[allow(clippy::too_many_arguments)] +pub fn mc_chroma( + reference: &[u8], + cw: usize, + ch: usize, + x0: usize, + y0: usize, + bw: usize, + bh: usize, + mvx: i32, + mvy: i32, + out: &mut [u8], +) { + let _g = crate::prof::scope(crate::prof::Stage::InterMc); + if abl_mc() { + out.fill(128); + return; + } + let (ix0, iy0) = (x0 as isize + (mvx >> 3) as isize, y0 as isize + (mvy >> 3) as isize); + let (fx, fy) = (mvx & 7, mvy & 7); + // Full-pel and fully inside the frame: `(64·a + 32) >> 6 == a`, a verbatim copy. + // Skip the per-pixel bilinear + 4× clamped `at()`; copy row-wise. Bit-identical. + if fx == 0 + && fy == 0 + && ix0 >= 0 + && iy0 >= 0 + && ix0 + bw as isize <= cw as isize + && iy0 + bh as isize <= ch as isize + && reference.len() >= cw * ch + { + let (rx, ry) = (ix0 as usize, iy0 as usize); + // Const-8 fast path for the full 8×8 chroma block (skip / P_16x16 common + // case): fixed-size slices → inline 8-byte moves, not a runtime-length + // `memcpy` call per row. Byte-identical. See the luma twin in `mc_luma`. + if bw == 8 && bh == 8 { + for dy in 0..8 { + let src = &reference[(ry + dy) * cw + rx..]; + out[dy * 8..dy * 8 + 8].copy_from_slice(&src[..8]); + } + } else { + for dy in 0..bh { + let src = &reference[(ry + dy) * cw + rx..][..bw]; + out[dy * bw..dy * bw + bw].copy_from_slice(src); + } + } + return; + } + // Sub-pel (and full-pel edge): extract the clamped (bw+1)×(bh+1) tile once — + // the edge-extended input `McChromaWithFragMv_c` reads — then the bilinear + // `A·p + B·p₊₁ + C·p₊ₛ + D·p₊ₛ₊₁` (`g_kuiABCD` weights), `(·+32)>>6`. A chroma + // block is at most 8×8 (half a 16×16 MB), so a 9×9 tile suffices. Bit-identical: + // the clamped tile reproduces `at()`, and full-pel weights give `(64·a+32)>>6==a`. + let ts = bw + 1; + let mut t = [0u8; 9 * 9]; + // Interior fast path (see `luma_tile`): clamp-free contiguous row copies. + if ix0 >= 0 + && iy0 >= 0 + && ix0 + ts as isize <= cw as isize + && iy0 + (bh + 1) as isize <= ch as isize + && reference.len() >= cw * ch + { + let (rx0, ry0) = (ix0 as usize, iy0 as usize); + for ty in 0..bh + 1 { + let src = (ry0 + ty) * cw + rx0; + t[ty * ts..ty * ts + ts].copy_from_slice(&reference[src..src + ts]); + } + } else { + for ty in 0..bh + 1 { + let ry = (iy0 + ty as isize).clamp(0, ch as isize - 1) as usize * cw; + for tx in 0..ts { + let rx = (ix0 + tx as isize).clamp(0, cw as isize - 1) as usize; + t[ty * ts + tx] = reference.get(ry + rx).copied().unwrap_or(0); + } + } + } + let (wa, wb, wc, wd) = ((8 - fx) * (8 - fy), fx * (8 - fy), (8 - fx) * fy, fx * fy); + // 8-wide chroma (full-MB and 16×16-partition chroma — the common case) → the + // openh264 SSE2 bilinear over the same clamped tile. Width 2/4 stay scalar + // (width-4 is only an MMX kernel; width 2 has none). Bit-identical. + #[cfg(accel)] + if bw == 8 { + let abcd = [wa as u8, wb as u8, wc as u8, wd as u8]; + rusty_h264_accel::mc_chroma_w8(&t, ts, out, bw, &abcd, bh); + return; + } + for r in 0..bh { + for c in 0..bw { + let p = r * ts + c; + let v = wa * t[p] as i32 + + wb * t[p + 1] as i32 + + wc * t[p + ts] as i32 + + wd * t[p + ts + 1] as i32; + out[r * bw + c] = ((v + 32) >> 6) as u8; + } + } +} + +// ---- Padded-reference MC (openh264 ExpandPicture style) ---- +// +// A reference plane is stored with a replicated-edge border (`PAD_L` luma / +// `PAD_C` chroma pixels), the picture origin at `(pad, pad)` and `stride` = the +// padded width. MC then reads the frame DIRECTLY at the MV offset — no per-call +// clamped tile — because reads into the border hit valid replicated pixels. For +// the rare MV whose 6-tap halo would exceed the border, we fall back to the +// clamped tile (reading the padded interior), which is bit-identical to the +// exact-frame path. +// +// STATUS: implemented + bit-exact (the `mc_*_padded_matches_exact` tests + a full +// decoder wiring verified 35/35 corpus MATCH), but measured **~0** vs the tile +// path on x86-64 — once `luma_tile`'s interior fast path made extraction a +// vectorized copy, the remaining win (skipping the copy) is offset by the +// padded direct read's worse kernel cache locality (full-frame stride vs the +// L1-resident tile) plus the per-frame expand/copy cost. Kept UNWIRED as a ready +// option for a workload/target where tile extraction dominates (e.g. slower +// memory, or hand-asm kernels tuned for the big-stride read). To wire: store +// `RefFrame` planes padded (`expand_plane` in `as_reference`) and call these +// instead of `mc_luma`/`mc_chroma`. + +/// Luma reference border width (covers full-pel MVs to ±30 px before fallback). +pub const PAD_L: usize = 32; +/// Chroma reference border width (= `PAD_L`/2, matching the half-rate chroma MV). +pub const PAD_C: usize = 16; + +/// Fills the `pad`-wide replicated-edge border of a plane whose picture (`pw×ph`) +/// sits at offset `(pad, pad)` with `stride`. Mirrors openh264 `ExpandPictureLuma_c`: +/// left/right cols replicate the edge pixel; top/bottom rows replicate the (already +/// edge-filled) first/last picture row, so the corners come out right. +pub fn expand_plane(buf: &mut [u8], stride: usize, pad: usize, pw: usize, ph: usize) { + for y in 0..ph { + let row = (y + pad) * stride; + let (left, right) = (buf[row + pad], buf[row + pad + pw - 1]); + for x in 0..pad { + buf[row + x] = left; + buf[row + pad + pw + x] = right; + } + } + let first = pad * stride; + let last = (pad + ph - 1) * stride; + for y in 0..pad { + buf.copy_within(first..first + stride, y * stride); + buf.copy_within(last..last + stride, (pad + ph + y) * stride); + } +} + +/// Quarter-pel luma MC reading a padded reference directly (no clamped tile when +/// the halo is in-border). `x0,y0` are the block's picture coords; `stride`/`pad` +/// describe the padded plane; `pw,ph` are the picture dims. Bit-identical to +/// [`mc_luma`] on the equivalent exact frame. +#[allow(clippy::too_many_arguments)] +/// MEASUREMENT KNOB — `RFF_ABL_MC=1` makes both padded motion-compensation +/// primitives return immediately with a flat block, pricing INTER PREDICTION by +/// ablation on the UNINSTRUMENTED binary. +/// +/// Placed inside the two primitives rather than at their ~13 decoder call sites so +/// the ablation cannot miss one, and so every caller, every call COUNT and all the +/// surrounding glue (partition walk, MV derivation, buffer setup) stay exactly as +/// they were — what is priced is the interpolation work itself, nothing else. +/// +/// Frame count is unaffected: parsing and residual decoding are untouched. Output +/// pixels are wrong while this is set, by design — it is never a shipping path. +/// Read once; the branch predicts perfectly. +#[inline] +pub(crate) fn abl_mc() -> bool { + use std::sync::atomic::{AtomicU8, Ordering}; + static ON: AtomicU8 = AtomicU8::new(0); + match ON.load(Ordering::Relaxed) { + 1 => true, + 2 => false, + _ => { + let on = std::env::var_os("RFF_ABL_MC").is_some_and(|v| v != "0"); + ON.store(if on { 1 } else { 2 }, Ordering::Relaxed); + on + } + } +} + +pub fn mc_luma_padded( + padded: &[u8], + stride: usize, + pad: usize, + pw: usize, + ph: usize, + x0: usize, + y0: usize, + bw: usize, + bh: usize, + mvx: i32, + mvy: i32, + out: &mut [u8], +) { + with_mc_scratch(|scr| mc_luma_padded_pre(scr, padded, stride, pad, pw, ph, x0, y0, bw, bh, mvx, mvy, out)) +} + +/// [`mc_luma_padded`] with the scratch pre-borrowed (see [`with_mc_scratch`]). +#[allow(clippy::too_many_arguments)] +pub fn mc_luma_padded_pre( + scr: &mut McScratch, + padded: &[u8], + stride: usize, + pad: usize, + pw: usize, + ph: usize, + x0: usize, + y0: usize, + bw: usize, + bh: usize, + mvx: i32, + mvy: i32, + out: &mut [u8], +) { + let _g = crate::prof::scope(crate::prof::Stage::InterMc); + let (ix0, iy0) = (x0 as isize + (mvx >> 2) as isize, y0 as isize + (mvy >> 2) as isize); + let (fx, fy) = (mvx & 3, mvy & 3); + // Size x phase census for the DECODER's MC. The facility existed but was wired + // only into `mc_luma` (the encoder's), so the decoder's own distribution had + // never been measured -- and it is the one that decides which const-width fast + // paths are worth having. + #[cfg(feature = "profile")] + mcstats::record(bw, bh, fx, fy); + #[cfg(feature = "profile")] + let _mcg = McCycleGuard { b: mcstats::bucket(bw, bh, fx, fy), t: crate::prof::tick() }; + let p = pad as isize; + let (lo_x, lo_y) = (ix0 - 2, iy0 - 2); + // Malformed-stream armor: a mutated stream can hand a reference whose plane + // no longer matches the caller's geometry (mid-stream SPS change). The fast + // paths index arithmetically, so they require the buffer to be intact; the + // fallback below reads checked. One compare on the hot path. + let intact = stride >= pw + 2 * pad && padded.len() >= stride * (ph + 2 * pad); + let in_range = intact + && lo_x >= -p + && lo_y >= -p + && lo_x + (bw + 5) as isize <= pw as isize + p + && lo_y + (bh + 5) as isize <= ph as isize + p; + if in_range { + if fx == 0 && fy == 0 { + // CONST-WIDTH row copies. With a runtime `bw` each row lowers to a + // variable-length `memcpy` CALL, and the census priced a 16x16 full-pel + // copy at 377 cycles -- ~10x what 256 bytes should cost. H.264 emits + // only these five widths. + macro_rules! rows { + ($n:expr) => {{ + for dy in 0..bh { + let src = ((iy0 + dy as isize + p) as usize) * stride + (ix0 + p) as usize; + out[dy * $n..dy * $n + $n].copy_from_slice(&padded[src..src + $n]); + } + }}; + } + match bw { + 16 => rows!(16), + 8 => rows!(8), + 4 => rows!(4), + _ => { + for dy in 0..bh { + let src = ((iy0 + dy as isize + p) as usize) * stride + (ix0 + p) as usize; + out[dy * bw..dy * bw + bw].copy_from_slice(&padded[src..src + bw]); + } + } + } + } else { + let halo = ((lo_y + p) as usize) * stride + (lo_x + p) as usize; + mc_luma_subpel(&padded[halo..], stride, bw, bh, fx, fy, &mut scr.a, &mut scr.b, out); + } + return; + } + // Extreme MV: clamp the halo to the real picture, read the padded interior. + let ts = bw + 5; + let mut t = [0u8; LUMA_TILE * LUMA_TILE]; + for ty in 0..bh + 5 { + let py = (lo_y + ty as isize).clamp(0, ph as isize - 1) as usize; + let ry = (py + pad) * stride; + for tx in 0..ts { + let px = (lo_x + tx as isize).clamp(0, pw as isize - 1) as usize; + // Checked: on intact buffers this never misses; on malformed ones a + // grey sample beats a panic (no conformance duty on garbage input). + t[ty * ts + tx] = padded.get(ry + px + pad).copied().unwrap_or(128); + } + } + if fx == 0 && fy == 0 { + for dy in 0..bh { + let s = (dy + 2) * ts + 2; + out[dy * bw..dy * bw + bw].copy_from_slice(&t[s..s + bw]); + } + } else { + mc_luma_subpel(&t, ts, bw, bh, fx, fy, &mut scr.a, &mut scr.b, out); + } +} + +/// Eighth-pel chroma MC reading a padded reference directly. Bit-identical to +/// [`mc_chroma`] on the equivalent exact frame. +#[allow(clippy::too_many_arguments)] +pub fn mc_chroma_padded( + padded: &[u8], + stride: usize, + pad: usize, + pw: usize, + ph: usize, + x0: usize, + y0: usize, + bw: usize, + bh: usize, + mvx: i32, + mvy: i32, + out: &mut [u8], +) { + let _g = crate::prof::scope(crate::prof::Stage::InterMc); + let (ix0, iy0) = (x0 as isize + (mvx >> 3) as isize, y0 as isize + (mvy >> 3) as isize); + let (fx, fy) = (mvx & 7, mvy & 7); + let p = pad as isize; + let intact = stride >= pw + 2 * pad && padded.len() >= stride * (ph + 2 * pad); + let in_range = intact + && ix0 >= -p + && iy0 >= -p + && ix0 + (bw + 1) as isize <= pw as isize + p + && iy0 + (bh + 1) as isize <= ph as isize + p; + let (wa, wb, wc, wd) = ((8 - fx) * (8 - fy), fx * (8 - fy), (8 - fx) * fy, fx * fy); + if in_range { + if fx == 0 && fy == 0 { + for dy in 0..bh { + let src = ((iy0 + dy as isize + p) as usize) * stride + (ix0 + p) as usize; + out[dy * bw..dy * bw + bw].copy_from_slice(&padded[src..src + bw]); + } + return; + } + let halo = ((iy0 + p) as usize) * stride + (ix0 + p) as usize; + #[cfg(accel)] + { + // H-38: BOTH widths now take asm. The 4-wide path was missing, so every + // 8×8 B-direct sub-block and sub-8×8 partition fell to the scalar + // bilinear below — chroma MC then cost as much as luma on half the + // pixels. Both kernels are pinned bit-identical to that scalar arm. + let abcd = [wa as u8, wb as u8, wc as u8, wd as u8]; + if bw == 8 { + rusty_h264_accel::mc_chroma_w8(&padded[halo..], stride, out, bw, &abcd, bh); + return; + } + if bw == 4 { + rusty_h264_accel::mc_chroma_w4(&padded[halo..], stride, out, bw, &abcd, bh); + return; + } + } + for r in 0..bh { + for c in 0..bw { + let pp = halo + r * stride + c; + let v = wa * padded[pp] as i32 + + wb * padded[pp + 1] as i32 + + wc * padded[pp + stride] as i32 + + wd * padded[pp + stride + 1] as i32; + out[r * bw + c] = ((v + 32) >> 6) as u8; + } + } + return; + } + // Extreme MV: clamp the (bw+1)² halo to the real picture, read the padded interior. + let ts = bw + 1; + let mut t = [0u8; 9 * 9]; + for ty in 0..bh + 1 { + let py = (iy0 + ty as isize).clamp(0, ph as isize - 1) as usize; + let ry = (py + pad) * stride; + for tx in 0..ts { + let px = (ix0 + tx as isize).clamp(0, pw as isize - 1) as usize; + t[ty * ts + tx] = padded.get(ry + px + pad).copied().unwrap_or(128); + } + } + for r in 0..bh { + for c in 0..bw { + let pp = r * ts + c; + let v = wa * t[pp] as i32 + + wb * t[pp + 1] as i32 + + wc * t[pp + ts] as i32 + + wd * t[pp + ts + 1] as i32; + out[r * bw + c] = ((v + 32) >> 6) as u8; + } + } +} + +#[cfg(test)] +mod tests { + use super::*; + + fn rand_plane(pw: usize, ph: usize, seed: u32) -> Vec { + let mut s = seed; + (0..pw * ph) + .map(|_| { + s = s.wrapping_mul(1103515245).wrapping_add(12345); + (s >> 16) as u8 + }) + .collect() + } + + fn make_padded(exact: &[u8], pw: usize, ph: usize, pad: usize) -> (Vec, usize) { + let stride = pw + 2 * pad; + let mut padded = vec![0u8; stride * (ph + 2 * pad)]; + for y in 0..ph { + let d = (y + pad) * stride + pad; + padded[d..d + pw].copy_from_slice(&exact[y * pw..y * pw + pw]); + } + expand_plane(&mut padded, stride, pad, pw, ph); + (padded, stride) + } + + #[test] + fn mc_luma_padded_matches_exact() { + let (pw, ph) = (48usize, 32usize); + let exact = rand_plane(pw, ph, 0x77); + let (padded, stride) = make_padded(&exact, pw, ph, PAD_L); + for &(bw, bh) in &[(16usize, 16usize), (8, 8), (16, 8), (8, 16), (4, 4)] { + for x0 in [0usize, 8, pw - bw] { + for y0 in [0usize, 8, ph - bh] { + for mvx in [-40i32, -20, -3, 0, 1, 2, 3, 7, 20, 40] { + for mvy in [-40i32, -20, -3, 0, 1, 2, 3, 7, 20, 40] { + let mut a = vec![0u8; bw * bh]; + let mut b = vec![0u8; bw * bh]; + mc_luma(&exact, pw, ph, x0, y0, bw, bh, mvx, mvy, &mut a); + mc_luma_padded( + &padded, stride, PAD_L, pw, ph, x0, y0, bw, bh, mvx, mvy, &mut b, + ); + assert_eq!(a, b, "luma bw={bw} x0={x0} y0={y0} mv=({mvx},{mvy})"); + } + } + } + } + } + } + + #[test] + fn mc_chroma_padded_matches_exact() { + let (pw, ph) = (24usize, 16usize); + let exact = rand_plane(pw, ph, 0x99); + let (padded, stride) = make_padded(&exact, pw, ph, PAD_C); + for &(bw, bh) in &[(8usize, 8usize), (4, 4), (8, 4), (4, 8), (2, 2)] { + for x0 in [0usize, 4, pw - bw] { + for y0 in [0usize, 4, ph - bh] { + for mvx in [-40i32, -16, -3, 0, 1, 5, 8, 16, 40] { + for mvy in [-40i32, -16, -3, 0, 1, 5, 8, 16, 40] { + let mut a = vec![0u8; bw * bh]; + let mut b = vec![0u8; bw * bh]; + mc_chroma(&exact, pw, ph, x0, y0, bw, bh, mvx, mvy, &mut a); + mc_chroma_padded( + &padded, stride, PAD_C, pw, ph, x0, y0, bw, bh, mvx, mvy, &mut b, + ); + assert_eq!(a, b, "chroma bw={bw} x0={x0} y0={y0} mv=({mvx},{mvy})"); + } + } + } + } + } + } + + /// Campaign-3 oracle: the fused single-pass builder must fill H/V/C + /// byte-for-byte like the tile-walk builder, across geometries whose padded + /// dimensions are and are not multiples of 16 (partial edge tiles) and with + /// enough randomness to exercise the clip. + #[test] + fn fused_hpel_builder_matches_tiles() { + let mut st = 0x5eed_f00d_dead_beefu64; + let mut lcg = move || { + st = st.wrapping_mul(6364136223846793005).wrapping_add(1442695040888963407); + (st >> 33) as u8 + }; + for &(cw, ch, pad) in &[(64usize, 48usize, 16usize), (80, 64, 12), (176, 144, 32)] { + let reference: Vec = (0..cw * ch).map(|_| lcg()).collect(); + let (pw, ph) = (cw + 2 * pad, ch + 2 * pad); + // The same edge-replicated padded source `build_hpel_planes` constructs. + let mut f = vec![0u8; pw * ph]; + for y in 0..ph { + let sy = (y as isize - pad as isize).clamp(0, ch as isize - 1) as usize; + let row = &reference[sy * cw..sy * cw + cw]; + let d = &mut f[y * pw..y * pw + pw]; + d[..pad].fill(row[0]); + d[pad..pad + cw].copy_from_slice(row); + d[pad + cw..].fill(row[cw - 1]); + } + let (mut h1, mut v1, mut c1) = (vec![0u8; pw * ph], vec![0u8; pw * ph], vec![0u8; pw * ph]); + let (mut h2, mut v2, mut c2) = (vec![0u8; pw * ph], vec![0u8; pw * ph], vec![0u8; pw * ph]); + build_hpel_tiles(&f, pw, ph, &mut h1, &mut v1, &mut c1); + build_hpel_fused(&f, pw, ph, &mut h2, &mut v2, &mut c2); + assert_eq!(h1, h2, "H plane differs at {cw}x{ch} pad {pad}"); + assert_eq!(v1, v2, "V plane differs at {cw}x{ch} pad {pad}"); + assert_eq!(c1, c2, "C plane differs at {cw}x{ch} pad {pad}"); + // AVX2 fused kernel: byte-identical to the scalar fused builder (and + // transitively to the tiles) on every geometry, including widths whose + // vector interior leaves scalar tails. + #[cfg(accel)] + { + let (mut h3, mut v3, mut c3) = + (vec![0u8; pw * ph], vec![0u8; pw * ph], vec![0u8; pw * ph]); + if rusty_h264_accel::hpel_fused(&f, pw, ph, &mut h3, &mut v3, &mut c3) { + assert_eq!(h1, h3, "AVX2 H plane differs at {cw}x{ch} pad {pad}"); + assert_eq!(v1, v3, "AVX2 V plane differs at {cw}x{ch} pad {pad}"); + assert_eq!(c1, c3, "AVX2 C plane differs at {cw}x{ch} pad {pad}"); + } + } + } + } + + /// The plane cache must be BIT-IDENTICAL to `mc_luma` wherever it applies — + /// that identity is what keeps the motion search's decisions, and therefore the + /// bitstream, unchanged. Sweeps every sub-pel phase, every block size, and a + /// range of positions including ones near the frame edge (where it must decline). + #[test] + fn hpel_block_matches_mc_luma_exactly() { + let (cw, ch) = (96usize, 64usize); + let mut reference = vec![0u8; cw * ch]; + let mut s: u32 = 0x9E37_79B9; + for p in reference.iter_mut() { + s = s.wrapping_mul(1_664_525).wrapping_add(1_013_904_223); + *p = (s >> 24) as u8; + } + let planes = build_hpel_planes(&reference, cw, ch); + + let mut checked = 0; + for (bw, bh) in [(16, 16), (16, 8), (8, 16), (8, 8), (8, 4), (4, 8), (4, 4)] { + for fy in 0..4i32 { + for fx in 0..4i32 { + if fx == 0 && fy == 0 { + continue; // full-pel is the copy path, not the plane path + } + for y0 in (0..ch - bh).step_by(7) { + for x0 in (0..cw - bw).step_by(5) { + for &(dx, dy) in &[(0i32, 0i32), (4, 0), (0, 4), (-4, -4), (8, 8), (-64, -64), (96, 40), (-96, 60), (40, -96)] { + let (mvx, mvy) = (dx + fx, dy + fy); + let mut want = [0u8; 256]; + mc_luma(&reference, cw, ch, x0, y0, bw, bh, mvx, mvy, &mut want); + let mut got = [0u8; 256]; + if !hpel_block(&planes, x0, y0, bw, bh, mvx, mvy, &mut got) { + continue; // declined (edge) -> caller falls back + } + assert_eq!( + &got[..bw * bh], + &want[..bw * bh], + "bw={bw} bh={bh} fx={fx} fy={fy} x0={x0} y0={y0} mv=({mvx},{mvy})" + ); + checked += 1; + } + } + } + } + } + } + assert!(checked > 5_000, "too few positions exercised: {checked}"); + } + + #[test] + fn mc_luma_block_kernels_match_per_pixel() { + // The block-kernel MC must be bit-identical to the per-pixel `luma_sample` + // reference for every quarter-pel position, across interior AND edge blocks + // (negative / off-frame MVs that exercise the clamped tile vs `at()`). + let (cw, ch) = (40usize, 32usize); + let mut state = 0x1357_9bdfu32; + let mut next = || { + state = state.wrapping_mul(1_664_525).wrapping_add(1_013_904_223); + (state >> 24) as u8 + }; + let reference: Vec = (0..cw * ch).map(|_| next()).collect(); + for &(bw, bh) in &[(16, 16), (8, 8), (4, 4), (8, 16), (16, 8)] { + for &(x0, y0) in &[(8usize, 8usize), (0, 0), (cw - bw, ch - bh)] { + for mvx in -9..=9 { + for mvy in -9..=9 { + let mut got = vec![0u8; bw * bh]; + mc_luma(&reference, cw, ch, x0, y0, bw, bh, mvx, mvy, &mut got); + let ix0 = x0 as isize + (mvx >> 2) as isize; + let iy0 = y0 as isize + (mvy >> 2) as isize; + let (fx, fy) = (mvx & 3, mvy & 3); + for dy in 0..bh { + for dx in 0..bw { + let want = luma_sample( + &reference, cw, ch, + ix0 + dx as isize, iy0 + dy as isize, fx, fy, + ) as u8; + assert_eq!( + got[dy * bw + dx], want, + "bw{bw}x{bh} at ({x0},{y0}) mv({mvx},{mvy}) px({dx},{dy})" + ); + } + } + } + } + } + } + } + + #[test] + fn mc_chroma_block_matches_per_pixel() { + let (cw, ch) = (24usize, 20usize); + let mut state = 0xabcd_1234u32; + let mut next = || { + state = state.wrapping_mul(1_664_525).wrapping_add(1_013_904_223); + (state >> 24) as u8 + }; + let reference: Vec = (0..cw * ch).map(|_| next()).collect(); + let pp = |ix: isize, iy: isize, fx: i32, fy: i32| -> u8 { + let a = at(&reference, cw, ch, ix, iy); + let b = at(&reference, cw, ch, ix + 1, iy); + let c = at(&reference, cw, ch, ix, iy + 1); + let d = at(&reference, cw, ch, ix + 1, iy + 1); + (((8 - fx) * (8 - fy) * a + fx * (8 - fy) * b + (8 - fx) * fy * c + fx * fy * d + 32) >> 6) + as u8 + }; + for &(bw, bh) in &[(8, 8), (4, 4), (8, 4), (4, 8)] { + for &(x0, y0) in &[(4usize, 4usize), (0, 0), (cw - bw, ch - bh)] { + for mvx in -12..=12 { + for mvy in -12..=12 { + let mut got = vec![0u8; bw * bh]; + mc_chroma(&reference, cw, ch, x0, y0, bw, bh, mvx, mvy, &mut got); + let ix0 = x0 as isize + (mvx >> 3) as isize; + let iy0 = y0 as isize + (mvy >> 3) as isize; + let (fx, fy) = (mvx & 7, mvy & 7); + for dy in 0..bh { + for dx in 0..bw { + assert_eq!( + got[dy * bw + dx], + pp(ix0 + dx as isize, iy0 + dy as isize, fx, fy), + "bw{bw}x{bh} at ({x0},{y0}) mv({mvx},{mvy}) px({dx},{dy})" + ); + } + } + } + } + } + } + } + + #[test] + fn median_of_three() { + assert_eq!(median3(1, 2, 3), 2); + assert_eq!(median3(3, 1, 2), 2); + assert_eq!(median3(-5, 0, 5), 0); + assert_eq!(median3(7, 7, 2), 7); + } + + #[test] + fn mv_predict_single_neighbor_uses_it() { + let a = MvNeighbor { available: true, mv: (8, -4), ref_idx: 0 }; + // B and C unavailable, A available → predictor is A. + assert_eq!(predict_mv(a, MvNeighbor::NONE, MvNeighbor::NONE, 0), (8, -4)); + } + + #[test] + fn mv_predict_median_when_all_inter() { + let a = MvNeighbor { available: true, mv: (4, 0), ref_idx: 0 }; + let b = MvNeighbor { available: true, mv: (8, 0), ref_idx: 0 }; + let c = MvNeighbor { available: true, mv: (12, 0), ref_idx: 0 }; + assert_eq!(predict_mv(a, b, c, 0), (8, 0)); + } + + #[test] + fn mv_predict_one_matching_ref_wins() { + // Only B references ref 0; A and C are intra → predictor is B. + let a = MvNeighbor { available: true, mv: (0, 0), ref_idx: -1 }; + let b = MvNeighbor { available: true, mv: (5, 7), ref_idx: 0 }; + let c = MvNeighbor { available: true, mv: (0, 0), ref_idx: -1 }; + assert_eq!(predict_mv(a, b, c, 0), (5, 7)); + } + + #[test] + fn mv_predict_distinguishes_refs() { + // A references ref 1, B references ref 0, C intra. For cur_ref 0 only B + // matches → B; for cur_ref 1 only A matches → A. + let a = MvNeighbor { available: true, mv: (4, 4), ref_idx: 1 }; + let b = MvNeighbor { available: true, mv: (5, 7), ref_idx: 0 }; + let c = MvNeighbor { available: true, mv: (0, 0), ref_idx: -1 }; + assert_eq!(predict_mv(a, b, c, 0), (5, 7)); + assert_eq!(predict_mv(a, b, c, 1), (4, 4)); + } + + #[test] + fn mc_luma_zero_mv_copies() { + let reference = vec![ + 0, 1, 2, 3, 10, 11, 12, 13, 20, 21, 22, 23, 30, 31, 32, 33, + ]; + let mut out = [0u8; 4]; + mc_luma(&reference, 4, 4, 1, 1, 2, 2, 0, 0, &mut out); + assert_eq!(out, [11, 12, 21, 22]); + } + + #[test] + fn mc_luma_clamps_at_edges() { + let reference = vec![5, 6, 7, 8]; + let mut out = [0u8; 4]; + mc_luma(&reference, 2, 2, 0, 0, 2, 2, -40, -40, &mut out); + assert_eq!(out, [5, 5, 5, 5]); + } + + #[test] + fn mc_luma_halfpel_on_flat_is_flat() { + // A flat reference must interpolate to the same flat value at any frac. + let reference = vec![100u8; 8 * 8]; + let mut out = [0u8; 16]; + for &(fx, fy) in &[(2, 0), (0, 2), (2, 2), (1, 1), (3, 3)] { + mc_luma(&reference, 8, 8, 2, 2, 4, 4, fx, fy, &mut out); + assert!(out.iter().all(|&p| p == 100), "frac ({fx},{fy})"); + } + } + + #[test] + fn mc_chroma_zero_mv_copies() { + let reference = vec![0, 1, 2, 3, 10, 11, 12, 13, 20, 21, 22, 23, 30, 31, 32, 33]; + let mut out = [0u8; 4]; + mc_chroma(&reference, 4, 4, 1, 1, 2, 2, 0, 0, &mut out); + assert_eq!(out, [11, 12, 21, 22]); + } + + #[test] + fn mc_chroma_bilinear_midpoint() { + // Horizontal ramp 0,8; chroma frac 4 (half) → midpoint 4. + let reference = vec![0u8, 8, 0, 8]; + let mut out = [0u8; 1]; + mc_chroma(&reference, 2, 2, 0, 0, 1, 1, 4, 0, &mut out); + assert_eq!(out[0], 4); + } +} diff --git a/vendor/rusty_h264-common/src/lib.rs b/vendor/rusty_h264-common/src/lib.rs new file mode 100644 index 0000000..00e0e2c --- /dev/null +++ b/vendor/rusty_h264-common/src/lib.rs @@ -0,0 +1,57 @@ +//! Shared primitives for the `rusty_h264` pure-Rust H.264 codec. +//! +//! # Global allocator +//! +//! Upstream's `global-alloc` feature installed `rusty_alloc` as the process-wide +//! allocator here. This vendored copy does not (see the edith patch below the +//! crate attributes); the feature is kept declared but empty so the sibling +//! decoder/encoder manifests still resolve. The process uses the system +//! allocator. +//! +//! This crate is the foundation both the encoder and decoder sit on. It is +//! `#![forbid(unsafe_code)]`: the bit-twiddling core of an H.264 codec is +//! exactly where memory-safety bugs hide in the C implementations, so we keep +//! it provably safe. +//! +//! Modules mirror the concerns shared across `codec/common` in Cisco's +//! openh264: +//! - [`bit_writer`] / [`bit_reader`] — MSB-first bit packing + Exp-Golomb. +//! - [`nal`] — NAL units, Annex-B framing, RBSP emulation prevention. +//! - [`types`] — shared enums and the raw YUV frame container. +//! +//! The shipped build is `#![forbid(unsafe_code)]`. The `profile` feature (a +//! measurement-only dev build, never shipped) relaxes this to unlock the `rdtsc` +//! timer in [`prof`]; that is the *only* unsafe in the crate and only under `profile`. +#![cfg_attr(not(feature = "profile"), forbid(unsafe_code))] + +// --- edith patch: no process-wide allocator --- +// Upstream installed `rusty_alloc` as the whole application's +// `#[global_allocator]` here, under a feature its own decoder and encoder turn +// on by default. Under sustained seeking edith churns decode-worker threads, +// and that allocator faulted inside `span_from_segments` on a fresh thread's +// very first allocation. The codec is unchanged; only this declaration is gone, +// so the process keeps glibc's malloc. + +pub mod aligned; +pub mod bit_reader; +pub mod bit_writer; +pub mod cabac_tables; +pub mod cavlc; +pub mod deblock; + +/// Whether the vendored SIMD kernels are compiled in (`asm` feature on x86-64). +/// Exposed so benchmarks can state which path they measured — a harness that +/// silently falls back to the scalar twin reports numbers that look like a +/// regression in the fast path. +pub const ACCEL: bool = cfg!(accel); +pub mod inter; +pub mod nal; +pub mod predict; +pub mod prof; +pub mod transform; +pub mod types; + +pub use bit_reader::BitReader; +pub use bit_writer::BitWriter; +pub use nal::{NalUnit, NalUnitType}; +pub use types::{ChromaFormat, Profile, YuvFrame}; diff --git a/vendor/rusty_h264-common/src/nal.rs b/vendor/rusty_h264-common/src/nal.rs new file mode 100644 index 0000000..84a322d --- /dev/null +++ b/vendor/rusty_h264-common/src/nal.rs @@ -0,0 +1,232 @@ +//! NAL units, Annex-B framing, and RBSP emulation-prevention. +//! +//! H.264 carries syntax in NAL (Network Abstraction Layer) units. In the +//! Annex-B byte stream each NAL is prefixed by a start code (`00 00 01`, often +//! `00 00 00 01`). Within a NAL, the raw payload (RBSP) is escaped so the +//! start-code pattern can never appear by accident: any `00 00 00/01/02/03` +//! gets a `03` emulation-prevention byte inserted, producing the SODB/EBSP. + +/// NAL unit type (`nal_unit_type`, 5 bits). Only the subset relevant to a +/// Constrained Baseline encoder/decoder is named; others are `Other`. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub enum NalUnitType { + /// Coded slice of a non-IDR picture. + NonIdrSlice, + /// Coded slice of an IDR picture. + IdrSlice, + /// Supplemental enhancement information. + Sei, + /// Sequence parameter set. + Sps, + /// Picture parameter set. + Pps, + /// Access unit delimiter. + AccessUnitDelimiter, + /// Any type not specifically handled. + Other(u8), +} + +impl NalUnitType { + /// Numeric `nal_unit_type` value. + pub fn id(self) -> u8 { + match self { + NalUnitType::NonIdrSlice => 1, + NalUnitType::IdrSlice => 5, + NalUnitType::Sei => 6, + NalUnitType::Sps => 7, + NalUnitType::Pps => 8, + NalUnitType::AccessUnitDelimiter => 9, + NalUnitType::Other(v) => v & 0x1f, + } + } + + /// Parses a `nal_unit_type` value. + pub fn from_id(v: u8) -> Self { + match v & 0x1f { + 1 => NalUnitType::NonIdrSlice, + 5 => NalUnitType::IdrSlice, + 6 => NalUnitType::Sei, + 7 => NalUnitType::Sps, + 8 => NalUnitType::Pps, + 9 => NalUnitType::AccessUnitDelimiter, + other => NalUnitType::Other(other), + } + } +} + +/// A NAL unit: a header (type + `nal_ref_idc`) plus its raw RBSP payload. +#[derive(Debug, Clone)] +pub struct NalUnit { + /// `nal_ref_idc` (0..=3): non-zero marks the NAL as referenceable. + pub ref_idc: u8, + /// NAL unit type. + pub nal_type: NalUnitType, + /// Raw byte sequence payload (un-escaped). + pub rbsp: Vec, +} + +impl NalUnit { + /// Builds a NAL unit. + pub fn new(ref_idc: u8, nal_type: NalUnitType, rbsp: Vec) -> Self { + Self { + ref_idc, + nal_type, + rbsp, + } + } + + /// The one-byte NAL header: `forbidden_zero_bit(0) | nal_ref_idc | nal_unit_type`. + pub fn header_byte(&self) -> u8 { + ((self.ref_idc & 0x3) << 5) | self.nal_type.id() + } + + /// Appends this NAL to `out` as an Annex-B unit: 4-byte start code, header + /// byte, then the emulation-prevented payload. + pub fn write_annex_b(&self, out: &mut Vec) { + out.extend_from_slice(&[0x00, 0x00, 0x00, 0x01]); + out.push(self.header_byte()); + emulation_prevent_into(&self.rbsp, out); + } + + /// Serializes a single NAL as a standalone Annex-B byte stream. + pub fn to_annex_b(&self) -> Vec { + let mut out = Vec::with_capacity(self.rbsp.len() + 8); + self.write_annex_b(&mut out); + out + } +} + +/// Inserts emulation-prevention bytes, appending the EBSP to `out`. +/// +/// Whenever the next byte would complete a `00 00 00`, `00 00 01`, `00 00 02`, +/// or `00 00 03` sequence, a `03` is inserted after the two zeros. +pub fn emulation_prevent_into(rbsp: &[u8], out: &mut Vec) { + let mut zeros = 0usize; + for &b in rbsp { + if zeros >= 2 && b <= 0x03 { + out.push(0x03); + zeros = 0; + } + out.push(b); + if b == 0 { + zeros += 1; + } else { + zeros = 0; + } + } +} + +/// Removes emulation-prevention bytes from an EBSP payload, returning the RBSP. +pub fn emulation_unprevent(ebsp: &[u8]) -> Vec { + let mut out = Vec::with_capacity(ebsp.len()); + let mut zeros = 0usize; + let mut i = 0; + while i < ebsp.len() { + let b = ebsp[i]; + if zeros >= 2 && b == 0x03 && i + 1 < ebsp.len() && ebsp[i + 1] <= 0x03 { + // Drop this emulation-prevention byte. + zeros = 0; + i += 1; + continue; + } + out.push(b); + if b == 0 { + zeros += 1; + } else { + zeros = 0; + } + i += 1; + } + out +} + +/// Splits an Annex-B byte stream into raw NAL byte slices (header + EBSP), +/// stripping start codes. Does not parse headers or un-escape payloads. +pub fn split_annex_b(stream: &[u8]) -> Vec<&[u8]> { + let mut nals = Vec::new(); + let mut starts = Vec::new(); + let mut i = 0; + while i + 3 <= stream.len() { + if stream[i] == 0 && stream[i + 1] == 0 && stream[i + 2] == 1 { + starts.push(i + 3); + i += 3; + } else { + i += 1; + } + } + for (idx, &s) in starts.iter().enumerate() { + // The NAL runs to just before the next start code (minus any trailing + // zero bytes that belong to the next start code's prefix). + let end = if idx + 1 < starts.len() { + let next = starts[idx + 1] - 3; + // Trim the trailing zero of a 4-byte (00 00 00 01) start code. + if next > s && stream[next - 1] == 0 { + next - 1 + } else { + next + } + } else { + stream.len() + }; + if end > s { + nals.push(&stream[s..end]); + } + } + nals +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn header_byte_packs_fields() { + let nal = NalUnit::new(3, NalUnitType::Sps, vec![]); + // ref_idc=3 (11), type=7 (00111) => 0110_0111 + assert_eq!(nal.header_byte(), 0b0110_0111); + } + + #[test] + fn emulation_prevention_inserts_03() { + // Each inserted 0x03 resets the zero-run counter, so five zeros then a + // 1 escapes twice: 00 00 [03] 00 00 [03] 00 01. + let mut out = Vec::new(); + emulation_prevent_into(&[0, 0, 0, 0, 0, 1], &mut out); + assert_eq!(out, vec![0, 0, 3, 0, 0, 3, 0, 1]); + } + + #[test] + fn emulation_roundtrip() { + let payloads: &[&[u8]] = &[ + &[0, 0, 0, 1], + &[0, 0, 1, 2, 3], + &[1, 2, 3, 4, 5], + &[0, 0, 0, 0, 0, 0], + &[0, 0, 3, 0, 0, 3], + ]; + for p in payloads { + let mut ebsp = Vec::new(); + emulation_prevent_into(p, &mut ebsp); + assert_eq!(&emulation_unprevent(&ebsp), p, "roundtrip {p:?}"); + } + } + + #[test] + fn annex_b_split_and_unescape() { + let sps = NalUnit::new(3, NalUnitType::Sps, vec![0, 0, 1, 0x42]); + let pps = NalUnit::new(3, NalUnitType::Pps, vec![0xAB, 0xCD]); + let mut stream = Vec::new(); + sps.write_annex_b(&mut stream); + pps.write_annex_b(&mut stream); + + let nals = split_annex_b(&stream); + assert_eq!(nals.len(), 2); + + // First NAL: header byte then EBSP. + assert_eq!(NalUnitType::from_id(nals[0][0]), NalUnitType::Sps); + assert_eq!(emulation_unprevent(&nals[0][1..]), vec![0, 0, 1, 0x42]); + + assert_eq!(NalUnitType::from_id(nals[1][0]), NalUnitType::Pps); + assert_eq!(emulation_unprevent(&nals[1][1..]), vec![0xAB, 0xCD]); + } +} diff --git a/vendor/rusty_h264-common/src/predict.rs b/vendor/rusty_h264-common/src/predict.rs new file mode 100644 index 0000000..bb246eb --- /dev/null +++ b/vendor/rusty_h264-common/src/predict.rs @@ -0,0 +1,907 @@ +//! Intra prediction + shared block reconstruction for I_16x16 macroblocks. +//! +//! These routines are used identically by the encoder (to reconstruct each +//! macroblock so the next one can predict from it) and the decoder. Keeping +//! them in one place guarantees the two stay bit-for-bit in agreement, which is +//! what intra prediction requires. + +use crate::transform::inverse_core; + +/// 4×4 luma block scan order → (block-x, block-y) within a macroblock, in units +/// of 4 samples. This is the order luma residual blocks are coded and the order +/// neighbor `nnz` values are indexed by. +pub const LUMA_4X4_SCAN_XY: [(usize, usize); 16] = [ + (0, 0), (1, 0), (0, 1), (1, 1), + (2, 0), (3, 0), (2, 1), (3, 1), + (0, 2), (1, 2), (0, 3), (1, 3), + (2, 2), (3, 2), (2, 3), (3, 3), +]; + +/// Chroma 4×4 block scan order → (block-x, block-y) within the 8×8, in units of +/// 4 samples (simple raster for 4:2:0). +pub const CHROMA_4X4_SCAN_XY: [(usize, usize); 4] = [(0, 0), (1, 0), (0, 1), (1, 1)]; + +/// Maps a luma QP to its chroma QP (with `chroma_qp_index_offset == 0`). +/// MEASUREMENT KNOBS — ablation switches for pricing stages the scope profiler cannot +/// read (its per-call rdtsc tax at ~20M calls exceeds the thing being measured). +/// +/// `RFF_ABL_INTRA=1` makes every intra predictor return a flat block; `RFF_ABL_RECON=1` +/// makes reconstruction return the prediction unchanged (residual discarded). Both leave +/// PARSING and every call count untouched — what is priced is the pixel work alone, so +/// the frame count is unaffected and the work-parity check still holds. Output pixels +/// are wrong while either is set, by design; these are never a shipping path. +/// Read once; the branch predicts perfectly. +#[inline] +pub(crate) fn abl_intra() -> bool { + use std::sync::atomic::{AtomicU8, Ordering}; + static ON: AtomicU8 = AtomicU8::new(0); + match ON.load(Ordering::Relaxed) { + 1 => true, + 2 => false, + _ => { + let on = std::env::var_os("RFF_ABL_INTRA").is_some_and(|v| v != "0"); + ON.store(if on { 1 } else { 2 }, Ordering::Relaxed); + on + } + } +} + +#[inline] +pub(crate) fn abl_recon() -> bool { + use std::sync::atomic::{AtomicU8, Ordering}; + static ON: AtomicU8 = AtomicU8::new(0); + match ON.load(Ordering::Relaxed) { + 1 => true, + 2 => false, + _ => { + let on = std::env::var_os("RFF_ABL_RECON").is_some_and(|v| v != "0"); + ON.store(if on { 1 } else { 2 }, Ordering::Relaxed); + on + } + } +} + +pub fn chroma_qp(qp: u8) -> u8 { + + const QPC: [u8; 22] = [ + 29, 30, 31, 32, 32, 33, 34, 34, 35, 35, 36, 36, 37, 37, 37, 38, 38, 38, 39, 39, 39, 39, + ]; + if qp < 30 { + qp + } else { + QPC[(qp - 30) as usize] + } +} + +/// CAVLC `nC` context from the left (`a`) and top (`b`) neighbor block `nnz` +/// counts (`None` = neighbor unavailable). +pub fn nc_from_neighbors(a: Option, b: Option) -> i32 { + match (a, b) { + (Some(na), Some(nb)) => (na as i32 + nb as i32 + 1) >> 1, + (Some(na), None) => na as i32, + (None, Some(nb)) => nb as i32, + (None, None) => 0, + } +} + +fn sum(s: &[u8]) -> i32 { + s.iter().map(|&x| x as i32).sum() +} + +/// Intra_16x16 DC luma prediction: a single value used for all 256 samples. +pub fn luma16x16_dc(avail_top: bool, avail_left: bool, top: &[u8; 16], left: &[u8; 16]) -> u8 { + let v = if avail_top && avail_left { + (sum(top) + sum(left) + 16) >> 5 + } else if avail_top { + (sum(top) + 8) >> 4 + } else if avail_left { + (sum(left) + 8) >> 4 + } else { + 128 + }; + v as u8 +} + +/// The four `Intra_16x16` prediction modes (spec §8.3.3). The discriminant is +/// the `intra16x16_pred_mode` value carried in `mb_type`. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub enum I16Mode { + Vertical = 0, + Horizontal = 1, + Dc = 2, + Plane = 3, +} + +impl I16Mode { + /// Parses a mode number (0..=3). + pub fn from_id(v: u32) -> Self { + match v & 3 { + 0 => I16Mode::Vertical, + 1 => I16Mode::Horizontal, + 2 => I16Mode::Dc, + _ => I16Mode::Plane, + } + } + + /// Whether this mode is usable given neighbor availability. + pub fn available(self, avail_top: bool, avail_left: bool) -> bool { + match self { + I16Mode::Vertical => avail_top, + I16Mode::Horizontal => avail_left, + I16Mode::Dc => true, + I16Mode::Plane => avail_top && avail_left, + } + } +} + +/// Computes the 16×16 luma prediction for an `Intra_16x16` macroblock, returning +/// 256 raster samples. `corner` is the above-left neighbor (used by Plane). +pub fn luma16x16_pred( + mode: I16Mode, + avail_top: bool, + avail_left: bool, + top: &[u8; 16], + left: &[u8; 16], + corner: u8, +) -> [u8; 256] { + if abl_intra() { + return [128; 256]; + } + let _g = crate::prof::scope(crate::prof::Stage::IntraPred); + let mut out = [0u8; 256]; + match mode { + I16Mode::Vertical => { + for y in 0..16 { + for x in 0..16 { + out[y * 16 + x] = top[x]; + } + } + } + I16Mode::Horizontal => { + for y in 0..16 { + for x in 0..16 { + out[y * 16 + x] = left[y]; + } + } + } + I16Mode::Dc => { + let v = luma16x16_dc(avail_top, avail_left, top, left); + out.fill(v); + } + I16Mode::Plane => { + // p[x,-1] = top[x] (x 0..15), p[-1,y] = left[y], p[-1,-1] = corner. + let tp = |i: isize| -> i32 { + if i < 0 { + corner as i32 + } else { + top[i as usize] as i32 + } + }; + let lf = |i: isize| -> i32 { + if i < 0 { + corner as i32 + } else { + left[i as usize] as i32 + } + }; + let mut h = 0i32; + let mut v = 0i32; + for xp in 0..8i32 { + h += (xp + 1) * (tp(8 + xp as isize) - tp(6 - xp as isize)); + } + for yp in 0..8i32 { + v += (yp + 1) * (lf(8 + yp as isize) - lf(6 - yp as isize)); + } + let a = 16 * (left[15] as i32 + top[15] as i32); + let b = (5 * h + 32) >> 6; + let c = (5 * v + 32) >> 6; + for y in 0..16i32 { + for x in 0..16i32 { + let val = (a + b * (x - 7) + c * (y - 7) + 16) >> 5; + out[(y * 16 + x) as usize] = clip_u8(val); + } + } + } + } + out +} + +/// Intra 4×4 luma prediction (spec §8.3.1.2), all 9 modes. Returns 16 raster +/// samples. Neighbors: `top[0..4]` above, `top[4..8]` above-right (the caller +/// substitutes `top[3]` when the above-right block is unavailable), `left[0..4]` +/// to the left, `corner` above-left. `avail_top`/`avail_left` gate DC only; +/// callers must not select a mode whose neighbors are unavailable. +pub fn intra4x4_pred( + mode: u8, + avail_top: bool, + avail_left: bool, + top: &[u8; 8], + left: &[u8; 4], + corner: u8, +) -> [u8; 16] { + if abl_intra() { + return [128; 16]; + } + let _g = crate::prof::scope(crate::prof::Stage::IntraPred); + let t = |i: usize| top[i] as i32; + let l = |i: usize| left[i] as i32; + let c = corner as i32; + // Top/left indexed with -1 → corner. + let tt = |k: i32| -> i32 { + if k < 0 { + c + } else { + top[k as usize] as i32 + } + }; + let ll = |k: i32| -> i32 { + if k < 0 { + c + } else { + left[k as usize] as i32 + } + }; + + let mut p = [0i32; 16]; + match mode { + 0 => { + for y in 0..4 { + for x in 0..4 { + p[y * 4 + x] = t(x); + } + } + } + 1 => { + for y in 0..4 { + for x in 0..4 { + p[y * 4 + x] = l(y); + } + } + } + 2 => { + let v = if avail_top && avail_left { + (t(0) + t(1) + t(2) + t(3) + l(0) + l(1) + l(2) + l(3) + 4) >> 3 + } else if avail_top { + (t(0) + t(1) + t(2) + t(3) + 2) >> 2 + } else if avail_left { + (l(0) + l(1) + l(2) + l(3) + 2) >> 2 + } else { + 128 + }; + p.fill(v); + } + 3 => { + // Diagonal down-left + for y in 0..4 { + for x in 0..4 { + p[y * 4 + x] = if x == 3 && y == 3 { + (t(6) + 3 * t(7) + 2) >> 2 + } else { + let k = x + y; + (t(k) + 2 * t(k + 1) + t(k + 2) + 2) >> 2 + }; + } + } + } + 4 => { + // Diagonal down-right + for y in 0..4i32 { + for x in 0..4i32 { + p[(y * 4 + x) as usize] = if x > y { + (tt(x - y - 2) + 2 * tt(x - y - 1) + tt(x - y) + 2) >> 2 + } else if x < y { + (ll(y - x - 2) + 2 * ll(y - x - 1) + ll(y - x) + 2) >> 2 + } else { + (t(0) + 2 * c + l(0) + 2) >> 2 + }; + } + } + } + 5 => { + // Vertical-right + for y in 0..4i32 { + for x in 0..4i32 { + let zvr = 2 * x - y; + let k = x - (y >> 1); + p[(y * 4 + x) as usize] = if zvr >= 0 && zvr % 2 == 0 { + (tt(k - 1) + tt(k) + 1) >> 1 + } else if zvr >= 0 { + (tt(k - 2) + 2 * tt(k - 1) + tt(k) + 2) >> 2 + } else if zvr == -1 { + (l(0) + 2 * c + t(0) + 2) >> 2 + } else { + (ll(y - 1) + 2 * ll(y - 2) + ll(y - 3) + 2) >> 2 + }; + } + } + } + 6 => { + // Horizontal-down + for y in 0..4i32 { + for x in 0..4i32 { + let zhd = 2 * y - x; + let k = y - (x >> 1); + p[(y * 4 + x) as usize] = if zhd >= 0 && zhd % 2 == 0 { + (ll(k - 1) + ll(k) + 1) >> 1 + } else if zhd >= 0 { + (ll(k - 2) + 2 * ll(k - 1) + ll(k) + 2) >> 2 + } else if zhd == -1 { + (l(0) + 2 * c + t(0) + 2) >> 2 + } else { + (tt(x - 1) + 2 * tt(x - 2) + tt(x - 3) + 2) >> 2 + }; + } + } + } + 7 => { + // Vertical-left + for y in 0..4 { + for x in 0..4 { + let k = x + (y >> 1); + p[y * 4 + x] = if y % 2 == 0 { + (t(k) + t(k + 1) + 1) >> 1 + } else { + (t(k) + 2 * t(k + 1) + t(k + 2) + 2) >> 2 + }; + } + } + } + _ => { + // Horizontal-up (mode 8) + for y in 0..4 { + for x in 0..4 { + let zhu = x + 2 * y; + let k = y + (x >> 1); + p[y * 4 + x] = if zhu <= 4 && zhu % 2 == 0 { + (l(k) + l(k + 1) + 1) >> 1 + } else if zhu < 5 { + (l(k) + 2 * l(k + 1) + l(k + 2) + 2) >> 2 + } else if zhu == 5 { + (l(2) + 3 * l(3) + 2) >> 2 + } else { + l(3) + }; + } + } + } + } + let mut out = [0u8; 16]; + for i in 0..16 { + out[i] = clip_u8(p[i]); + } + out +} + +/// Intra chroma 8×8 DC prediction (spec §8.3.4): the 8×8 is split into four 4×4 +/// regions, each predicted from its available neighbor run. Returns the 64 +/// predicted samples in raster order. `top`/`left` are the 8 neighbor samples. +pub fn chroma8x8_dc(avail_top: bool, avail_left: bool, top: &[u8; 8], left: &[u8; 8]) -> [u8; 64] { + let mut out = [128u8; 64]; + for &(bx, by) in &CHROMA_4X4_SCAN_XY { + let (x0, y0) = (bx * 4, by * 4); + let top4 = &top[x0..x0 + 4]; + let left4 = &left[y0..y0 + 4]; + // Which neighbor each region prefers (spec §8.3.4.1). + let prefer_top = (x0, y0) == (4, 0); + let prefer_left = (x0, y0) == (0, 4); + let dc: i32 = if prefer_top { + if avail_top { + (sum(top4) + 2) >> 2 + } else if avail_left { + (sum(left4) + 2) >> 2 + } else { + 128 + } + } else if prefer_left { + if avail_left { + (sum(left4) + 2) >> 2 + } else if avail_top { + (sum(top4) + 2) >> 2 + } else { + 128 + } + } else { + // (0,0) and (4,4): use both when available. + if avail_top && avail_left { + (sum(top4) + sum(left4) + 4) >> 3 + } else if avail_top { + (sum(top4) + 2) >> 2 + } else if avail_left { + (sum(left4) + 2) >> 2 + } else { + 128 + } + }; + for dy in 0..4 { + for dx in 0..4 { + out[(y0 + dy) * 8 + (x0 + dx)] = dc as u8; + } + } + } + out +} + +/// Intra chroma 8×8 prediction (spec §8.3.4), all four modes. `mode`: +/// 0 = DC, 1 = Horizontal, 2 = Vertical, 3 = Plane. `top`/`left` are the 8 +/// neighbor samples; `corner` is the above-left (Plane only). +pub fn chroma8x8_pred( + mode: u8, + avail_top: bool, + avail_left: bool, + top: &[u8; 8], + left: &[u8; 8], + corner: u8, +) -> [u8; 64] { + if abl_intra() { + return [128; 64]; + } + let _g = crate::prof::scope(crate::prof::Stage::IntraPred); + match mode { + 1 => { + // Horizontal + let mut out = [0u8; 64]; + for y in 0..8 { + for x in 0..8 { + out[y * 8 + x] = left[y]; + } + } + out + } + 2 => { + // Vertical + let mut out = [0u8; 64]; + for y in 0..8 { + for x in 0..8 { + out[y * 8 + x] = top[x]; + } + } + out + } + 3 => { + // Plane + let tt = |k: i32| if k < 0 { corner as i32 } else { top[k as usize] as i32 }; + let ll = |k: i32| if k < 0 { corner as i32 } else { left[k as usize] as i32 }; + let mut h = 0i32; + let mut v = 0i32; + for xp in 0..4i32 { + h += (xp + 1) * (top[(4 + xp) as usize] as i32 - tt(2 - xp)); + } + for yp in 0..4i32 { + v += (yp + 1) * (left[(4 + yp) as usize] as i32 - ll(2 - yp)); + } + let a = 16 * (left[7] as i32 + top[7] as i32); + let b = (17 * h + 16) >> 5; + let c = (17 * v + 16) >> 5; + let mut out = [0u8; 64]; + for y in 0..8i32 { + for x in 0..8i32 { + out[(y * 8 + x) as usize] = clip_u8((a + b * (x - 3) + c * (y - 3) + 16) >> 5); + } + } + out + } + _ => chroma8x8_dc(avail_top, avail_left, top, left), + } +} + +/// Whether a chroma prediction mode is usable given neighbor availability. +pub fn chroma_mode_available(mode: u8, avail_top: bool, avail_left: bool) -> bool { + match mode { + 0 => true, // DC + 1 => avail_left, // Horizontal + 2 => avail_top, // Vertical + _ => avail_top && avail_left, // Plane + } +} + +/// Clips a value to the 8-bit pixel range. +#[inline] +pub fn clip_u8(v: i32) -> u8 { + v.clamp(0, 255) as u8 +} + +/// Reconstructs a 4×4 block: inverse-transform the dequantized coefficients and +/// add the prediction, clipping to 8-bit. `dequant` and `pred` are raster 4×4. +pub fn reconstruct_4x4(dequant: &[i32; 16], pred: &[i32; 16]) -> [u8; 16] { + if abl_recon() { + return std::array::from_fn(|i| clip_u8(pred[i])); + } + let _g = crate::prof::scope(crate::prof::Stage::Reconstruct); + add_residual_4x4(&inverse_core(dequant), pred) +} + +/// Reconstructs a 4×4 block DIRECTLY into the frame plane: IDCT + add + clip + +/// store in one pass, with the prediction read strided from its buffer. Kills +/// the per-block `predb` i32 gather, the `[u8; 16]` result array, and the +/// separate `store` call — the resid-add boundary the WHYS Part 8/9 descent +/// priced. Honors the same ablation knob as `reconstruct_4x4`. +#[inline] +pub fn reconstruct_4x4_into( + deq: &[i32; 16], + pred: &[u8], + p_off: usize, + p_stride: usize, + rec: &mut [u8], + r_off: usize, + r_stride: usize, +) { + if abl_recon() { + for r in 0..4 { + for c in 0..4 { + rec[r_off + r * r_stride + c] = pred[p_off + r * p_stride + c]; + } + } + return; + } + let _g = crate::prof::scope(crate::prof::Stage::Reconstruct); + let res = crate::transform::inverse_core(deq); + for r in 0..4 { + for c in 0..4 { + rec[r_off + r * r_stride + c] = + clip_u8(pred[p_off + r * p_stride + c] as i32 + res[r * 4 + c]); + } + } +} + +/// Flat-residual twin of [`reconstruct_4x4_into`] (the DC-only fast path). +#[inline] +pub fn reconstruct_4x4_dc_into( + rval: i32, + pred: &[u8], + p_off: usize, + p_stride: usize, + rec: &mut [u8], + r_off: usize, + r_stride: usize, +) { + if abl_recon() { + for r in 0..4 { + for c in 0..4 { + rec[r_off + r * r_stride + c] = pred[p_off + r * p_stride + c]; + } + } + return; + } + let _g = crate::prof::scope(crate::prof::Stage::Reconstruct); + for r in 0..4 { + for c in 0..4 { + rec[r_off + r * r_stride + c] = + clip_u8(pred[p_off + r * p_stride + c] as i32 + rval); + } + } +} + +/// Reconstructs a block whose residual is FLAT (every position carries the same +/// value `r`) — the tail of the DC-only fast path. Honors the same ablation +/// knob and profiling stage as [`reconstruct_4x4`] so measurement arms stay +/// comparable whichever path a block takes. +#[inline] +pub fn reconstruct_4x4_dc(r: i32, pred: &[i32; 16]) -> [u8; 16] { + if abl_recon() { + return std::array::from_fn(|i| clip_u8(pred[i])); + } + let _g = crate::prof::scope(crate::prof::Stage::Reconstruct); + std::array::from_fn(|i| clip_u8(pred[i] + r)) +} + +/// Adds an already-inverse-transformed residual block to its prediction and clips +/// to `u8`. Split out of [`reconstruct_4x4`] so callers that batch the inverse DCT +/// ([`crate::transform::inverse_dct_blocks`]) can share the add+clip tail. +#[inline] +pub fn add_residual_4x4(res: &[i32; 16], pred: &[i32; 16]) -> [u8; 16] { + let mut out = [0u8; 16]; + for i in 0..16 { + out[i] = clip_u8(pred[i] + res[i]); + } + out +} + +/// Intra_8x8 luma prediction (spec §8.3.2.2), all nine modes. Reference samples +/// are first low-pass filtered (§8.3.2.2.1) then the per-mode formulas — which +/// mirror the 4×4 ones over the 8-wide block — are applied. `top` holds the 16 +/// samples p[0..15,-1] (8..15 substituted by the caller when no top-right), +/// `left` the 8 samples p[-1,0..7], `corner` is p[-1,-1]; `avail_corner` is the +/// above-left neighbor's availability. Returns 64 predicted samples (raster). +#[allow(clippy::needless_range_loop)] // filter loops read neighbors p[k-1..k+1] +pub fn intra8x8_pred( + mode: u8, + avail_top: bool, + avail_left: bool, + avail_corner: bool, + top: &[u8; 16], + left: &[u8; 8], + corner: u8, +) -> [u8; 64] { + let _g = crate::prof::scope(crate::prof::Stage::IntraPred); + // ---- reference sample filtering (§8.3.2.2.1) ---- + let t = |k: usize| top[k] as i32; + let l = |k: usize| left[k] as i32; + let cc = corner as i32; + let mut ft = [0i32; 16]; + ft[0] = if avail_corner { + (cc + 2 * t(0) + t(1) + 2) >> 2 + } else { + (3 * t(0) + t(1) + 2) >> 2 + }; + for k in 1..15 { + ft[k] = (t(k - 1) + 2 * t(k) + t(k + 1) + 2) >> 2; + } + ft[15] = (t(14) + 3 * t(15) + 2) >> 2; + let mut fl = [0i32; 8]; + fl[0] = if avail_corner { + (cc + 2 * l(0) + l(1) + 2) >> 2 + } else { + (3 * l(0) + l(1) + 2) >> 2 + }; + for k in 1..7 { + fl[k] = (l(k - 1) + 2 * l(k) + l(k + 1) + 2) >> 2; + } + fl[7] = (l(6) + 3 * l(7) + 2) >> 2; + let fc = if avail_corner { + if avail_top && avail_left { + (t(0) + 2 * cc + l(0) + 2) >> 2 + } else if avail_top { + (3 * cc + t(0) + 2) >> 2 + } else if avail_left { + (3 * cc + l(0) + 2) >> 2 + } else { + cc + } + } else { + cc + }; + // Indexers with -1 → filtered corner (for the diagonal modes). + let ttf = |k: i32| -> i32 { + if k < 0 { + fc + } else { + ft[k as usize] + } + }; + let llf = |k: i32| -> i32 { + if k < 0 { + fc + } else { + fl[k as usize] + } + }; + + let mut p = [0i32; 64]; + match mode { + 0 => { + for y in 0..8 { + for x in 0..8 { + p[y * 8 + x] = ft[x]; + } + } + } + 1 => { + for y in 0..8 { + for x in 0..8 { + p[y * 8 + x] = fl[y]; + } + } + } + 2 => { + let st: i32 = ft[0..8].iter().sum(); + let sl: i32 = fl[0..8].iter().sum(); + let v = if avail_top && avail_left { + (st + sl + 8) >> 4 + } else if avail_top { + (st + 4) >> 3 + } else if avail_left { + (sl + 4) >> 3 + } else { + 128 + }; + p.fill(v); + } + 3 => { + for y in 0..8 { + for x in 0..8 { + p[y * 8 + x] = if x == 7 && y == 7 { + (ft[14] + 3 * ft[15] + 2) >> 2 + } else { + (ft[x + y] + 2 * ft[x + y + 1] + ft[x + y + 2] + 2) >> 2 + }; + } + } + } + 4 => { + for y in 0..8i32 { + for x in 0..8i32 { + p[(y * 8 + x) as usize] = if x > y { + (ttf(x - y - 2) + 2 * ttf(x - y - 1) + ttf(x - y) + 2) >> 2 + } else if x < y { + (llf(y - x - 2) + 2 * llf(y - x - 1) + llf(y - x) + 2) >> 2 + } else { + (ft[0] + 2 * fc + fl[0] + 2) >> 2 + }; + } + } + } + 5 => { + for y in 0..8i32 { + for x in 0..8i32 { + let zvr = 2 * x - y; + let k = x - (y >> 1); + p[(y * 8 + x) as usize] = if zvr >= 0 && zvr % 2 == 0 { + (ttf(k - 1) + ttf(k) + 1) >> 1 + } else if zvr >= 0 { + (ttf(k - 2) + 2 * ttf(k - 1) + ttf(k) + 2) >> 2 + } else if zvr == -1 { + (fl[0] + 2 * fc + ft[0] + 2) >> 2 + } else { + let j = y - 2 * x; + (llf(j - 1) + 2 * llf(j - 2) + llf(j - 3) + 2) >> 2 + }; + } + } + } + 6 => { + for y in 0..8i32 { + for x in 0..8i32 { + let zhd = 2 * y - x; + let k = y - (x >> 1); + p[(y * 8 + x) as usize] = if zhd >= 0 && zhd % 2 == 0 { + (llf(k - 1) + llf(k) + 1) >> 1 + } else if zhd >= 0 { + (llf(k - 2) + 2 * llf(k - 1) + llf(k) + 2) >> 2 + } else if zhd == -1 { + (fl[0] + 2 * fc + ft[0] + 2) >> 2 + } else { + let j = x - 2 * y; + (ttf(j - 1) + 2 * ttf(j - 2) + ttf(j - 3) + 2) >> 2 + }; + } + } + } + 7 => { + for y in 0..8 { + for x in 0..8 { + let k = x + (y >> 1); + p[y * 8 + x] = if y % 2 == 0 { + (ft[k] + ft[k + 1] + 1) >> 1 + } else { + (ft[k] + 2 * ft[k + 1] + ft[k + 2] + 2) >> 2 + }; + } + } + } + _ => { + // Horizontal-up (mode 8) — 8×8 thresholds (zHU up to 13 special). + for y in 0..8 { + for x in 0..8 { + let zhu = x + 2 * y; + let k = y + (x >> 1); + p[y * 8 + x] = if zhu < 13 && zhu % 2 == 0 { + (fl[k] + fl[k + 1] + 1) >> 1 + } else if zhu < 13 { + (fl[k] + 2 * fl[k + 1] + fl[k + 2] + 2) >> 2 + } else if zhu == 13 { + (fl[6] + 3 * fl[7] + 2) >> 2 + } else { + fl[7] + }; + } + } + } + } + let mut out = [0u8; 64]; + for i in 0..64 { + out[i] = clip_u8(p[i]); + } + out +} + +/// Reconstructs an 8×8 block: inverse-transform the dequantized coefficients, +/// add the prediction, clip. (The 8×8 inverse transform lives in `transform`.) +pub fn add_residual_8x8(res: &[i32; 64], pred: &[i32; 64]) -> [u8; 64] { + let _g = crate::prof::scope(crate::prof::Stage::Reconstruct); + let mut out = [0u8; 64]; + for i in 0..64 { + out[i] = clip_u8(pred[i] + res[i]); + } + out +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn intra8x8_dc_no_neighbors_is_128() { + let p = intra8x8_pred(2, false, false, false, &[0; 16], &[0; 8], 0); + assert!(p.iter().all(|&v| v == 128)); + } + + #[test] + fn intra8x8_vertical_copies_filtered_top() { + // Flat top → filtered top is the same flat value → every column equals it. + let p = intra8x8_pred(0, true, false, false, &[90; 16], &[0; 8], 0); + assert!(p.iter().all(|&v| v == 90)); + } + + #[test] + fn intra8x8_horizontal_is_constant_per_row() { + let mut left = [0u8; 8]; + for (i, v) in left.iter_mut().enumerate() { + *v = (10 * i + 20) as u8; + } + let p = intra8x8_pred(1, false, true, false, &[0; 16], &left, 0); + // Each row constant; filtering blurs values but row 0..7 stay monotone-ish. + for y in 0..8 { + for x in 1..8 { + assert_eq!(p[y * 8 + x], p[y * 8], "row {y} not constant"); + } + } + } + + #[test] + fn luma_dc_no_neighbors_is_128() { + assert_eq!(luma16x16_dc(false, false, &[0; 16], &[0; 16]), 128); + } + + #[test] + fn luma_dc_averages_neighbors() { + let top = [100u8; 16]; + let left = [200u8; 16]; + // (1600 + 3200 + 16) >> 5 = 150 + assert_eq!(luma16x16_dc(true, true, &top, &left), 150); + assert_eq!(luma16x16_dc(true, false, &top, &left), 100); + assert_eq!(luma16x16_dc(false, true, &top, &left), 200); + } + + #[test] + fn chroma_dc_unavailable_is_128() { + let p = chroma8x8_dc(false, false, &[0; 8], &[0; 8]); + assert!(p.iter().all(|&x| x == 128)); + } + + #[test] + fn chroma_qp_mapping() { + assert_eq!(chroma_qp(20), 20); + assert_eq!(chroma_qp(30), 29); + assert_eq!(chroma_qp(51), 39); + } + + #[test] + fn nc_derivation() { + assert_eq!(nc_from_neighbors(Some(3), Some(4)), 4); + assert_eq!(nc_from_neighbors(Some(5), None), 5); + assert_eq!(nc_from_neighbors(None, None), 0); + } + + #[test] + fn intra4x4_vertical_copies_top() { + let top = [10, 20, 30, 40, 0, 0, 0, 0]; + let p = intra4x4_pred(0, true, false, &top, &[0; 4], 0); + for y in 0..4 { + assert_eq!(&p[y * 4..y * 4 + 4], &[10, 20, 30, 40]); + } + } + + #[test] + fn intra4x4_horizontal_copies_left() { + let left = [11, 22, 33, 44]; + let p = intra4x4_pred(1, false, true, &[0; 8], &left, 0); + for y in 0..4 { + assert!(p[y * 4..y * 4 + 4].iter().all(|&v| v == left[y])); + } + } + + #[test] + fn intra4x4_dc_averages() { + let top = [10, 10, 10, 10, 0, 0, 0, 0]; + let left = [30, 30, 30, 30]; + // (40 + 120 + 4) >> 3 = 20 + let p = intra4x4_pred(2, true, true, &top, &left, 0); + assert!(p.iter().all(|&v| v == 20)); + // top only: (40 + 2) >> 2 = 10 + let p2 = intra4x4_pred(2, true, false, &top, &left, 0); + assert!(p2.iter().all(|&v| v == 10)); + // neither: 128 + let p3 = intra4x4_pred(2, false, false, &top, &left, 0); + assert!(p3.iter().all(|&v| v == 128)); + } +} diff --git a/vendor/rusty_h264-common/src/prof.rs b/vendor/rusty_h264-common/src/prof.rs new file mode 100644 index 0000000..ac5811d --- /dev/null +++ b/vendor/rusty_h264-common/src/prof.rs @@ -0,0 +1,585 @@ +//! Feature-gated decode/encode **stage profiler** — the instrument for perf work. +//! +//! Zero cost unless the `profile` feature is enabled: with it off, [`scope`] is a +//! no-op returning a ZST guard that the optimizer elides entirely, so release +//! builds are byte-identical and the hot path is untouched. With it on, each +//! kernel times itself into an atomic nanosecond bucket; [`dump`] prints the +//! per-stage breakdown. +//! +//! Design mirrors `rff-codec-mp3`'s `encode::prof`. The kernels (`mc_luma`, +//! `reconstruct_4x4`, `decode_residual_block`, the intra predictors, `deblock`) +//! each open a [`scope`] at their top, so every call is captured with one edit. +//! A [`Stage::Total`] scope wraps the whole `decode()` call; the **`mgmt/other`** +//! line is the residue (`Total − Σ stages`) — i.e. per-MB management, MV +//! prediction, nnz/grid bookkeeping, dequant — the bucket we most want to shrink. +//! +//! Caveat for honest reading: the fine-grained buckets (`reconstruct`, `entropy`) +//! are entered millions of times, so each carries ~one `Instant::now()` of timer +//! overhead — their share is mildly inflated and `mgmt/other` mildly deflated. +//! The `(N calls)` column lets you judge ns/call. Measure **throughput** with the +//! `profile` feature OFF (no timer overhead); use this breakdown only to rank +//! stages. + +/// A timed pipeline stage. Order matters: everything before [`Total`](Stage::Total) +/// is a sub-component summed for the `mgmt/other` residue. +#[derive(Clone, Copy)] +pub enum Stage { + Entropy = 0, + IntraPred = 1, + InterMc = 2, + Reconstruct = 3, + Deblock = 4, + // --- Phase 1: decomposition of the former "mgmt/other" residue --- + /// Inverse quantization (`dequantize*`, `inverse_quant_8x8`). + Dequant = 5, + /// Scattering a reconstructed block into the strided frame plane (`store`). + Scatter = 6, + /// Re-striding the MC output into the per-MB prediction buffer. + PredBuf = 7, + /// MV prediction + per-block motion/ref/coded grid writes. + MvGrid = 8, + // --- Phase 3 / ghost-tracking: further decomposition of the residue --- + /// Neighbour derivation for prediction (MV/ref/intra-mode availability + reads). + Neighbors = 9, + /// P_Skip / B_Skip reconstruction (the pred→rec copies + grid writes, no residual). + SkipRecon = 10, + /// Per-frame finalize: output-frame build (crop), DPB / reference management. + Finalize = 11, + /// Per-MB non-residual syntax parse (mb_skip_run, mb_type, cbp, mb_qp_delta). + Syntax = 12, + /// `as_reference` DPB plane clone (rec_y/u/v → RefFrame), split out of Finalize. + DpbClone = 13, + // --- Encoder stages (a disjoint top-level partition of encode(); the shared + // primitive scopes above — IntraPred/InterMc/Reconstruct/Deblock/Entropy — + // nest INSIDE these and give the within-stage breakdown) --- + /// `coded_source`: clamped copy of the source planes to the MB-aligned grid. + EncSource = 14, + /// P_Skip prediction + free-skip check (skip MC + SAD + commit). + EncSkip = 15, + /// Motion estimation: `best_part` (integer SAD search + sub-pel + SATD/λ cost). + EncMe = 16, + /// Intra mode cost inside the inter decision (`best_i16_sad`/`best_i16_satd`). + EncIntraCost = 17, + /// Coding a chosen inter MB (`encode_inter_mb`: MC, residual, T/Q, entropy, recon). + EncInterCode = 18, + /// Coding an intra MB (`encode_mb`: mode search + T/Q + entropy + recon). + EncIntraCode = 19, + /// Per-frame encoder finalize (deblock-info build + RefFrame handoff). + EncFinal = 20, + /// Forward transform + quantize (+ recon dequant/idct) inside MB coding — INFO (nested). + EncTq = 21, + /// CAVLC residual bit-writing — INFO (nested inside Enc*Code). + EncWrite = 22, + /// The skip free-check's forward T/Q proof — INFO (nested inside EncSkip). + EncFree = 23, + /// Per-frame encoder PREP before the macroblock loop (FrameEncoder grid + /// allocation, source copy, AQ/mb-tree QP maps, content pre-passes) — INFO + /// (nested; contains `EncSource`). + EncPrep = 24, + /// NAL assembly of the coded slice: RBSP emulation-prevention scan + the + /// Annex-B copy into the output buffer. A full byte-wise pass over the frame's + /// bitstream, invisible until it was named. + EncNal = 25, + /// The whole macroblock double-loop — INFO (nested; contains the Enc* per-MB + /// stages). `EncMbLoop − Σ(per-MB stages)` is the per-MB GLUE, the part of the + /// old `mgmt/other` that lives between the named steps. + EncMbLoop = 26, + /// Per-MB motion-vector predictor / neighbour-candidate build in the encode + /// loop (`mv_neighbors_block`) — INFO (nested inside `EncMbLoop`, part of the + /// per-MB glue being decomposed). + EncMvPred = 27, + /// CAVLC entropy EMIT for a planned macroblock (`emit_inter_cavlc` and the + /// intra equivalent): mb_type, ref_idx, mvd, cbp, mb_qp_delta and every + /// residual block. This sits OUTSIDE `plan_inter_mb`, so before it was named + /// the whole encoder-side entropy coder was landing in `mgmt/other`. + EncEmit = 28, + /// Per-MB boundary-strength derivation done INSIDE the encode loop — INFO + /// (nested in `EncMbLoop`). Named so the work moved out of deblocking can be + /// priced at its new location rather than inferred from stage deltas. + EncBs = 29, + /// Adaptive-quantization per-MB QP map (`aq_qp_map`) — a full-frame variance + /// pass that runs every frame because AQ is on by default. INFO (nested in + /// `EncPrep`). + EncAq = 30, + /// Sub-pel prediction served from the cached half-pel planes (`hpel_block`) — + /// INFO (nested in `EncMe`). Named because the plane cache MOVED the sub-pel + /// motion-search work out of `inter-mc`, and unnamed work is invisible work. + MeHpel = 31, + /// The motion search's SATD/SAD cost metric itself — INFO (nested in `EncMe`). + MeCost = 32, + /// Building the cached half-pel planes for one reference picture — INFO. + MeHpelBuild = 33, + /// ME: coarse-to-fine full-pel diamond — INFO (nested in `EncMe`). + MeDiamond = 34, + /// ME: sub-pel (half + quarter) refinement rings — INFO (nested in `EncMe`). + MeSubpel = 35, + /// ME: the stalled-diamond wide rescue grid — INFO (nested in `EncMe`). + MeRescue = 36, + /// Wraps the whole `decode()`/`encode()` call — the denominator. + Total = 37, + // --- H-32: decomposition of the decoder's per-MB residue (INFO, nested; + // indexes past `Total` are excluded from dump()'s residue sum) --- + /// CABAC P-inter MB branch, whole body (parse + MC + recon nested inside). + DecMbP = 38, + /// CABAC B MB branch, whole body. + DecMbB = 39, + /// CABAC intra path (mode parse + residual + recon), whole body. + DecMbI = 40, + /// B-direct derivation + MC (`decode_b_direct`) — INFO (nested in DecMbB). + DecBDirect = 41, + /// Bi-/uni-pred region MC + blend (`b_mc`) — INFO (nested in DecMbB). + DecBMc = 42, + /// Per-picture + per-slice setup: FrameDecoder grids, slice neighbour vecs. + DecSetup = 43, + /// B-direct DERIVATION only (neighbours, ref pick, colZero gather) — INFO. + DecBDeriv = 44, + /// B motion-grid commit (`b_set_motion`) — INFO (nested in DecMbB). + DecBSet = 45, + // --- H-38: decomposition of `b_mc` (INFO, nested in DecBMc) --- + /// Implicit-weight derivation (POC math + the integer divide). + DecBWeights = 46, + /// Luma MC calls inside `b_mc`. + DecBLuma = 47, + /// Chroma MC calls inside `b_mc`. + DecBChroma = 48, + /// The bi-pred blend / uni-pred row copies out of the staging buffers. + DecBBlend = 49, + // --- Entropy-stage decomposition (INFO, nested inside `Entropy`) — added for + // the CABAC/CAVLC diagnosis once sampled profiling made sub-scopes affordable. + /// CABAC residual: the coded_block_flag bin + its neighbour-context read. + EntCbf = 50, + /// CABAC residual: the significance-map loop (sig + last bins). + EntSig = 51, + /// CABAC residual: the level loop (one/abs/UEG0 bins + sign bypass). + EntLvl = 52, + /// CAVLC residual: the coeff_token VLC read. + CavTok = 53, + /// CAVLC residual: trailing-one signs + level prefix/suffix reads. + CavLvl = 54, + /// CAVLC residual: total_zeros + run_before reads and the scatter to scan order. + CavRun = 55, + /// Per-MB neighbour/state cache shuffling in the CABAC MB branches: the + /// mvd/ref 30-entry cache build, the 48-entry nzc cache build, and the mb_nzc + /// write-back — the state plumbing BETWEEN parse steps (INFO, nested). + DecStateCache = 56, + /// `add_inter_residual` whole body (INFO, nested): contains Dequant / + /// Reconstruct / Scatter leaves; body minus leaves = the residual-add glue + /// (nnz re-derivation scans, un-scan, pred gathers, loop skeleton). + DecResidAdd = 57, + /// The P-body MC staging block (INFO, nested): contains InterMc + PredBuf + /// leaves; block minus leaves = rect-ladder + staging-buffer cost. + DecMcStage = 58, + /// `pack_frame_into` — the per-frame MbPack build (INFO, nested in Deblock). + DebPack = 59, + /// Per-MB bS derivation inside `filter_frame`: kind gate, predicates, + /// packed/tile/blind derivation, bs materialization (INFO, nested in Deblock). + DebDerive = 60, + /// Annex-B start-code scan (`split_annex_b`) — a full byte-wise pass over the + /// WHOLE stream plus two Vec allocations. Entered ~once per access unit, so it + /// is in the low-call-count regime the profiler measures reliably. + DecNalSplit = 61, + /// RBSP emulation-prevention removal (`emulation_unprevent`) — a second full + /// byte-wise pass, one bounds-checked `push` per byte, into a fresh Vec per NAL. + DecRbsp = 62, + /// The 11 per-slice `vec![...; total_mbs]` neighbour-state allocations at the top + /// of `decode_slice_cabac_inner` (mvd grids alone are 64 B/MB each, twice). + DecSliceAlloc = 63, + /// The whole CABAC macroblock loop — INFO (nested; contains dec-mb-P/B/I). + /// `DecMbLoop - sum(dec-mb-*)` is the per-MB loop GLUE outside the MB bodies. + DecMbLoop = 64, + /// `row_hook` — on every MB after decode. Mid-row calls early-out (no scope) + /// unless `RS_H264_ROWHOOK_EAGER=1`. On row crossings: bS derive + filter / + /// EDC row handoff. INFO (nested in DecMbLoop; contains deb:derive + deblock). + /// + /// Call COUNT with the early-out ≈ MB rows/picture (exact). Quote ms only with + /// that count; per-MB eager scoping inflated both calls and self-tax. + DecRowHook = 65, +} + +/// Number of buckets. +pub const N: usize = 66; + +#[cfg(feature = "profile")] +mod imp { + use super::{Stage, N}; + use std::sync::atomic::{AtomicU64, Ordering}; + use std::sync::Mutex; + use std::time::Instant; + + /// Index of the first non-`Total` stage — the residue sum runs `0..SUB`. + const SUB: usize = Stage::Total as usize; + + /// A cheap monotonic tick. On x86_64 this is `rdtsc` (~5-10 ns, ~3-5× cheaper + /// than `Instant::now()` = QueryPerformanceCounter ~20-30 ns on Windows), which + /// is what dominated the profiler's own overhead (~1M scope entries × 2 calls). + /// Buckets accumulate *ticks*; `dump()` converts to ns via a run-length TSC + /// calibration (invariant TSC → ticks are wall-time-proportional). Elsewhere we + /// fall back to `Instant` nanos so the profiler still builds cross-arch. + #[cfg(target_arch = "x86_64")] + #[inline(always)] + fn ticks() -> u64 { + // SAFETY: `_rdtsc` is a pure timestamp read with no memory effects; it is + // `unsafe` only because it is a target intrinsic. Reordering is immaterial to + // coarse scope timing. Compiled only under `feature = "profile"` (dev tool). + unsafe { core::arch::x86_64::_rdtsc() } + } + #[cfg(not(target_arch = "x86_64"))] + #[inline(always)] + fn ticks() -> u64 { + use std::sync::OnceLock; + static EPOCH: OnceLock = OnceLock::new(); + EPOCH.get_or_init(Instant::now).elapsed().as_nanos() as u64 + } + + /// (wall-clock, tick-count) sampled at `reset()` — the calibration anchor read at + /// `dump()` to recover ns-per-tick. Touched twice per run, so its `Mutex` cost is + /// irrelevant next to the per-scope path. + static ANCHOR: Mutex> = Mutex::new(None); + + const NAMES: [&str; N] = [ + "entropy/cavlc", + "intra-pred", + "inter-mc", + "reconstruct", + "deblock", + "dequant", + "scatter(store)", + "pred-buf copy", + "mv+grid", + "neighbors", + "skip-recon", + "finalize", + "syntax-parse", + "dpb-clone", + "enc-source-copy", + "enc-skip-check", + "enc-me(best_part)", + "enc-intra-cost", + "enc-inter-code", + "enc-intra-code", + "enc-finalize", + "enc-T/Q(nested)", + "enc-cavlc-write(nested)", + "enc-skip-freecheck(nested)", + "enc-prep(nested)", + "enc-nal-assembly", + "enc-mb-loop(nested)", + "enc-mvpred(nested)", + "enc-cavlc-emit", + "enc-bs-derive(nested)", + "enc-aq-map(nested)", + "me-hpel-read(nested)", + "me-cost/satd(nested)", + "me-hpel-BUILD(nested)", + "me-diamond(nested)", + "me-subpel(nested)", + "me-rescue(nested)", + "TOTAL", + "dec-mb-P(nested)", + "dec-mb-B(nested)", + "dec-mb-I(nested)", + "b-direct(nested)", + "b-mc(nested)", + "dec-setup", + "b-deriv(nested)", + "b-setmotion(nested)", + "b:weights(nested)", + "b:luma-mc(nested)", + "b:chroma-mc(nested)", + "b:blend(nested)", + "ent:cbf(nested)", + "ent:sigmap(nested)", + "ent:levels(nested)", + "cav:token(nested)", + "cav:levels(nested)", + "cav:runs(nested)", + "state-cache(nested)", + "resid-add(nested)", + "mc-stage(nested)", + "deb:pack(nested)", + "deb:derive(nested)", + "dec-nal-split", + "dec-rbsp-unescape", + "dec-slice-alloc", + "dec-mb-loop(nested)", + "dec-row-hook(nested)", + ]; + + static NS: [AtomicU64; N] = [const { AtomicU64::new(0) }; N]; + static CALLS: [AtomicU64; N] = [const { AtomicU64::new(0) }; N]; + + /// SAMPLED PROFILING — the fix for the profiler's own tax. + /// + /// The scope guard is an rdtsc pair. At ~20M per-macroblock scopes that tax was + /// measured at **1.32-1.43x of whole decode**, which is why every per-MB stage + /// share in this codec has been untrustworthy and why the campaign fell back to + /// ablation (which can only price stages someone already put a knob on). + /// + /// Fix: only TIME one call in `RS_H264_PROF_SAMPLE` (default 1 = time every call, + /// preserving the old behaviour exactly). Sampled cycles are scaled back up by the + /// sampling period, so the SHARE each stage reports is unbiased — a stage that + /// takes x% of time is entered proportionally often, so timing 1-in-N calls + /// estimates the same x% with 1/N the tax. Call COUNTS stay exact (counting is a + /// single relaxed add, not an rdtsc pair, so it is not the expensive part). + /// + /// This is the standard statistical-profiling trade: precision for a smaller + /// probe. At N=64 the tax drops ~64x while a stage above ~1% still lands within a + /// few percent relative over 20M+ entries. + pub struct Guard { + stage: usize, + start: u64, + /// 0 = not timed. Otherwise the weight this sample carries: 1 for an exactly + /// timed call, N for a sampled one. + scale: u64, + } + + /// Calls below this are ALWAYS timed exactly, whatever the sampling period. + /// + /// Two reasons. (a) The tax is proportional to call count, so a stage entered a + /// few thousand times costs nothing to time in full — sampling it buys no speed. + /// (b) Sampling a low-count stage is statistically worthless: `Total` is entered + /// once per FRAME (60 calls on a 60-frame clip), so at N=64 it would estimate the + /// entire denominator from ONE sample. Since every share is a ratio to `Total`, + /// that one bad estimate would skew every share on the table — which is exactly + /// what the first N=64 run showed (every stage share rose together). + const EXACT_PREFIX: u64 = 8192; + + /// Sampling period. 1 = time everything (previous behaviour, and the default so + /// no existing measurement silently changes meaning). + pub(crate) static SAMPLE_N: std::sync::atomic::AtomicU64 = + std::sync::atomic::AtomicU64::new(0); + + /// Sampling period, ROUNDED UP TO A POWER OF TWO so the selection test is a mask + /// (1 cycle) and not a `u64` division (~20-40 cycles — as expensive as the rdtsc + /// it is meant to avoid, which would make the whole scheme pointless). + #[inline(always)] + fn sample_period() -> u64 { + match SAMPLE_N.load(Ordering::Relaxed) { + 0 => { + let n = std::env::var("RS_H264_PROF_SAMPLE") + .ok() + .and_then(|v| v.parse::().ok()) + .filter(|v| *v >= 1) + .unwrap_or(1) + .next_power_of_two(); + SAMPLE_N.store(n, Ordering::Relaxed); + n + } + n => n, + } + } + + impl Drop for Guard { + #[inline] + fn drop(&mut self) { + if self.scale != 0 { + let d = ticks().wrapping_sub(self.start); + // Weight by this sample's scale so the bucket estimates TOTAL cycles. + // The first EXACT_PREFIX calls carry weight 1 (they were all timed); + // the tail carries weight N. Sum = exact prefix + unbiased estimate of + // the remainder, so a short-running stage degrades to "fully timed" + // rather than to "one sample times N". + NS[self.stage].fetch_add(d.wrapping_mul(self.scale), Ordering::Relaxed); + } + CALLS[self.stage].fetch_add(1, Ordering::Relaxed); + } + } + + #[inline] + /// Descent E: the raw tick source, for census modules that accumulate cycles into + /// their own buckets rather than a `Stage`. + #[inline(always)] + pub fn tick() -> u64 { + ticks() + } + + pub fn scope(s: Stage) -> Guard { + let n = sample_period(); + let c = CALLS[s as usize].load(Ordering::Relaxed); + // Pick 1-in-N by HASHING the call index, not by striding it. + // + // A plain `c % N` stride aliases: decode work is intensely periodic (blocks + // per macroblock, macroblocks per row), so a power-of-two stride can lock onto + // the same position in that pattern every time and systematically sample only + // the cheap — or only the expensive — calls. Multiplying by the 64-bit golden + // ratio and taking high bits decorrelates the selection from any workload + // period, giving an unbiased 1-in-N at ~4 cycles (mul, shift, and, test). + const GOLDEN: u64 = 0x9E37_79B9_7F4A_7C15; + let scale = if n == 1 || c < EXACT_PREFIX { + 1 + } else if (c.wrapping_mul(GOLDEN) >> 32) & (n - 1) == 0 { + n + } else { + 0 + }; + Guard { + stage: s as usize, + start: if scale != 0 { ticks() } else { 0 }, + scale, + } + } + + /// Zero all buckets and sample the calibration anchor — call before a clean run. + pub fn reset() { + for a in NS.iter().chain(CALLS.iter()) { + a.store(0, Ordering::Relaxed); + } + *ANCHOR.lock().unwrap() = Some((Instant::now(), ticks())); + } + + /// Human-readable name for stage index `i` (`SUB` = the `TOTAL` row). + pub fn name(i: usize) -> &'static str { + NAMES.get(i).copied().unwrap_or("?") + } + + /// One calibrated reading: `(ms, calls)` per stage index `0..N` (index `SUB` is + /// `Total`). Buckets hold `rdtsc` cycles; ns/tick is recovered from the reset→now + /// anchor (elapsed wall / elapsed cycles — invariant TSC, so cycles are wall- + /// proportional). Lets a driver run many passes and take a per-stage median. + pub fn snapshot() -> [(f64, u64); N] { + let load = |i: usize| NS[i].load(Ordering::Relaxed); + let ns_per_tick = ANCHOR + .lock() + .unwrap() + .map(|(t0, c0)| { + let wall = t0.elapsed().as_nanos() as f64; + let cyc = ticks().wrapping_sub(c0) as f64; + if cyc > 0.0 { + wall / cyc + } else { + 1.0 + } + }) + .unwrap_or(1.0); + let mut out = [(0.0f64, 0u64); N]; + for (i, o) in out.iter_mut().enumerate() { + *o = (load(i) as f64 * ns_per_tick / 1e6, CALLS[i].load(Ordering::Relaxed)); + } + out + } + + /// Print the per-stage breakdown (does not reset). + pub fn dump() { + let s = snapshot(); + let total = s[SUB].0.max(1e-9); + let sub_sum: f64 = (0..SUB).map(|i| s[i].0).sum(); + let mgmt = (total - sub_sum).max(0.0); + let pct = |ms: f64| 100.0 * ms / total; + + eprintln!("\n--- decode stage profile (decode() wall = {total:.1} ms) ---"); + for i in 0..SUB { + eprintln!( + " {:<15} {:>8.1} ms {:>5.1}% ({} calls)", + NAMES[i], s[i].0, pct(s[i].0), s[i].1, + ); + } + eprintln!( + " {:<15} {:>8.1} ms {:>5.1}% <- the OTHER bucket: unnamed decode glue", + "mgmt/other", mgmt, pct(mgmt), + ); + eprintln!(" {:<15} {:>8.1} ms 100.0%", NAMES[SUB], total); + // Attribute OTHER using INFO scopes (nested; shares can overlap parents). + // These are the deployment-signal names for the 1T residue campaign. + let info = |st: Stage| s[st as usize]; + let loop_ms = info(Stage::DecMbLoop).0; + let mb_bodies = info(Stage::DecMbP).0 + info(Stage::DecMbB).0 + info(Stage::DecMbI).0; + let loop_glue = (loop_ms - mb_bodies).max(0.0); + eprintln!("--- OTHER attribution (INFO scopes; parents include children) ---"); + eprintln!( + " dec-mb-loop glue≈ {:>8.1} ms {:>5.1}% (loop {:.1} − P/B/I bodies {:.1})", + loop_glue, + pct(loop_glue), + loop_ms, + mb_bodies + ); + let row_hook = info(Stage::DecRowHook).0; + let deblock = s[Stage::Deblock as usize].0; + let syntax = s[Stage::Syntax as usize].0; + let inter = s[Stage::InterMc as usize].0; + let entropy = s[Stage::Entropy as usize].0; + // Residue naming: top-level OTHER is work NOT wrapped by stages 0..Total. + // INFO scopes after Total do not shrink OTHER — they NAME pieces of it. + // Reconcile the big pieces that live in OTHER (nested times overlap). + eprintln!("--- OTHER named (why ~45% is not a mystery kernel) ---"); + eprintln!( + " top-level leaves already subtract: entropy {:.1}% inter-mc {:.1}% deblock {:.1}% syntax {:.1}%", + pct(entropy), + pct(inter), + pct(deblock), + pct(syntax), + ); + eprintln!( + " in-OTHER orchestration (INFO; overlaps leaves): row-hook {:.1}% loop-glue {:.1}% (glue−hook≈{:.1}%)", + pct(row_hook), + pct(loop_glue), + pct((loop_glue - row_hook).max(0.0)), + ); + eprintln!( + " in-OTHER B glue (INFO nested): b-mc {:.1}% b-direct {:.1}% blend {:.1}% setmot {:.1}% deriv {:.1}%", + pct(info(Stage::DecBMc).0), + pct(info(Stage::DecBDirect).0), + pct(info(Stage::DecBBlend).0), + pct(info(Stage::DecBSet).0), + pct(info(Stage::DecBDeriv).0), + ); + eprintln!( + " in-OTHER resid/mc-stage (INFO): resid-add {:.1}% mc-stage {:.1}% — remainder ≈ timer tax + tiny parse glue", + pct(info(Stage::DecResidAdd).0), + pct(info(Stage::DecMcStage).0), + ); + for st in [ + Stage::DecMbB, + Stage::DecMbP, + Stage::DecMbI, + Stage::DecBDirect, + Stage::DecBMc, + Stage::DecRowHook, + Stage::DecResidAdd, + Stage::DecMcStage, + Stage::DecSetup, + Stage::DecSliceAlloc, + Stage::DecNalSplit, + Stage::DecRbsp, + ] { + let (ms, calls) = info(st); + if ms > 0.05 || calls > 0 { + eprintln!( + " {:<18} {:>8.1} ms {:>5.1}% ({} calls)", + NAMES[st as usize], + ms, + pct(ms), + calls + ); + } + } + } +} + +#[cfg(not(feature = "profile"))] +mod imp { + use super::{Stage, N}; + + /// No-op guard (ZST) — elided in release. + pub struct Guard; + + #[inline(always)] + pub fn scope(_s: Stage) -> Guard { + Guard + } + #[inline(always)] + pub fn reset() {} + #[inline(always)] + pub fn dump() {} + #[inline(always)] + pub fn snapshot() -> [(f64, u64); N] { + [(0.0, 0); N] + } + #[inline(always)] + pub fn name(_i: usize) -> &'static str { + "" + } +} + +pub use imp::{dump, name, reset, scope, snapshot, Guard}; +#[cfg(feature = "profile")] +pub use imp::tick; diff --git a/vendor/rusty_h264-common/src/transform.rs b/vendor/rusty_h264-common/src/transform.rs new file mode 100644 index 0000000..b8a1df1 --- /dev/null +++ b/vendor/rusty_h264-common/src/transform.rs @@ -0,0 +1,1561 @@ +//! H.264 4×4 residual transform and quantization (spec §8.5 / §8.6). +//! +//! H.264 uses a small integer approximation of the DCT — a 4×4 "core" transform +//! whose scaling is folded into the quantizer, so it is exactly invertible in +//! integer arithmetic. This module implements the forward path (encoder: +//! residual → coefficients → quantized levels) and the inverse path (decoder +//! and encoder-reconstruction: levels → coefficients → residual). +//! +//! Correctness here is non-negotiable: the levels we emit are dequantized by +//! every conforming decoder using the exact spec tables below, so the forward +//! quantizer must be the faithful inverse of that process. + +/// `normAdjust4x4` (spec Table — the dequant scaling V), indexed by `[QP % 6]` +/// then by position group (see [`pos_group`]). +const NORM_ADJUST: [[i32; 3]; 6] = [ + [10, 16, 13], + [11, 18, 14], + [13, 20, 16], + [14, 23, 18], + [16, 25, 20], + [18, 29, 23], +]; + +/// Forward quantization multipliers `MF`, indexed by `[QP % 6]` then position +/// group. Paired with [`NORM_ADJUST`] so reconstruction ≈ source. +const QUANT_MF: [[i32; 3]; 6] = [ + [13107, 5243, 8066], + [11916, 4660, 7490], + [10082, 4194, 6554], + [9362, 3647, 5825], + [8192, 3355, 5243], + [7282, 2893, 4559], +]; + +/// Position group within a 4×4 block: +/// - 0: both indices even — the (0,0),(0,2),(2,0),(2,2) positions, +/// - 1: both indices odd — (1,1),(1,3),(3,1),(3,3), +/// - 2: everything else. +#[inline] +fn pos_group(i: usize, j: usize) -> usize { + match (i % 2, j % 2) { + (0, 0) => 0, + (1, 1) => 1, + _ => 2, + } +} + +/// `pos_group` evaluated for all 16 raster positions — lets the hot quant/dequant +/// loops index a flat per-position table instead of recomputing the `(i%2, j%2)` +/// match per coefficient (openh264 stores per-position MF/dequant tables). +const POS_GROUP_FLAT: [usize; 16] = [0, 2, 0, 2, 2, 1, 2, 1, 0, 2, 0, 2, 2, 1, 2, 1]; + + +/// `16 · NORM_ADJUST` pre-expanded to a flat 16-entry LevelScale table per `qp % 6`. +const fn flatten_level_scale() -> [[i32; 16]; 6] { + let mut out = [[0i32; 16]; 6]; + let mut m = 0; + while m < 6 { + let mut idx = 0; + while idx < 16 { + out[m][idx] = 16 * NORM_ADJUST[m][POS_GROUP_FLAT[idx]]; + idx += 1; + } + m += 1; + } + out +} +const LEVEL_SCALE_FLAT: [[i32; 16]; 6] = flatten_level_scale(); + +/// One-dimensional forward core transform butterfly (rows of `Cf`). +#[inline] +fn fwd_1d(x0: i32, x1: i32, x2: i32, x3: i32) -> (i32, i32, i32, i32) { + let t0 = x0 + x3; + let t1 = x1 + x2; + let t2 = x1 - x2; + let t3 = x0 - x3; + (t0 + t1, 2 * t3 + t2, t0 - t1, t3 - 2 * t2) +} + +/// One-dimensional inverse core transform butterfly (rows of `Ci`). +#[inline] +fn inv_1d(d0: i32, d1: i32, d2: i32, d3: i32) -> (i32, i32, i32, i32) { + let e0 = d0 + d2; + let e1 = d0 - d2; + let e2 = (d1 >> 1) - d3; + let e3 = d1 + (d3 >> 1); + (e0 + e3, e1 + e2, e1 - e2, e0 - e3) +} + +/// Forward core transform `W = Cf · X · Cfᵀ` over a row-major 4×4 block. +/// The output coefficients are pre-quantization (scaling lives in the quantizer). +pub fn forward_core(block: &[i32; 16]) -> [i32; 16] { + let mut m = *block; + // Rows. + for r in 0..4 { + let (a, b, c, d) = fwd_1d(m[r * 4], m[r * 4 + 1], m[r * 4 + 2], m[r * 4 + 3]); + m[r * 4] = a; + m[r * 4 + 1] = b; + m[r * 4 + 2] = c; + m[r * 4 + 3] = d; + } + // Columns. + for c in 0..4 { + let (a, b, cc, d) = fwd_1d(m[c], m[4 + c], m[8 + c], m[12 + c]); + m[c] = a; + m[4 + c] = b; + m[8 + c] = cc; + m[12 + c] = d; + } + m +} + +/// Quantizes forward-transform coefficients to levels. `intra` selects the +/// rounding dead-zone offset (1/3 for intra, 1/6 for inter). +/// Scalar quantization. `dz_div` sets the rounding dead-zone: the offset added +/// before the right shift is `2^qbits / dz_div`, so a *smaller* `dz_div` rounds +/// up more (higher quality, more bits). Typical values: 6 for inter, 3 for an +/// I-frame that serves as a reference, 2 for all-intra (where the larger offset +/// is a net rate-distortion win — better-quantized blocks predict their +/// neighbors better, shrinking downstream residuals). +pub fn quantize(coeffs: &[i32; 16], qp: u8, dz_div: i64) -> [i32; 16] { + // openh264's quant STRUCTURE (`level = ((|c| + FF)·MF_oh) >> 16`, bit-identical to + // `WelsQuant4x4_sse2`'s pmulhuw high-word) carrying OUR deadzone, not openh264's: + // `FF = round(F / MF)` reproduces our `(|c|·MF + F) >> qbits` (to within a rare ±1), + // so RD is preserved AND the asm kernel becomes a drop-in. (Adopting openh264's own + // FF tables regressed intra −1.5 dB.) `MF_oh[qp] = MF · 2^(16-qbits)`. + let mf_oh = &QUANT_MF_OH[qp as usize]; + let ff = quant_dz_ff(qp, dz_div); + const POS: [usize; 16] = [0, 1, 2, 3, 4, 5, 6, 7, 0, 1, 2, 3, 4, 5, 6, 7]; + let mut out = [0i32; 16]; + for idx in 0..16 { + let p = POS[idx]; + let a = coeffs[idx].unsigned_abs() as i32; + let lvl = ((a + ff[p] as i32) * mf_oh[p] as i32) >> 16; + out[idx] = if coeffs[idx] < 0 { -lvl } else { lvl }; + } + out +} + +/// The 8-entry deadzone offset table `FF[pos] = round(F / MF)` reproducing our +/// `(|c|·MF + F) >> qbits` deadzone (`F = 2^qbits / dz_div`) inside openh264's +/// `((|c| + FF)·MF_oh) >> 16` quantizer — so the asm `WelsQuant*4x4` kernels quantize +/// bit-identically to our scalar [`quantize`]. Pair with [`QUANT_MF_OH`]`[qp]` as MF. +pub fn quant_dz_ff(qp: u8, dz_div: i64) -> [i16; 8] { + let m = (qp % 6) as usize; + let qbits = 15 + (qp / 6) as i64; + let f = (1i64 << qbits) / dz_div; + // Position (0:even/even, 1:odd/odd, 2:mixed) group of each of openh264's 8 slots. + const GROUP8: [usize; 8] = [0, 2, 0, 2, 2, 1, 2, 1]; + let mut ff = [0i16; 8]; + for (i, slot) in ff.iter_mut().enumerate() { + let mfg = QUANT_MF[m][GROUP8[i]] as i64; + *slot = ((f + mfg / 2) / mfg) as i16; + } + ff +} + +/// Rate-distortion–optimized ("trellis") quantization of a 4×4 residual's +/// transform coefficients. For each coefficient it chooses between the scalar +/// level and one lower (down to zero) to minimize `J = distortion + λ·rate`, +/// trading a few bits of coefficient coding for small reconstruction error. +/// `lambda` is the mode-decision Lagrangian (pixel-SSD domain). Encoder-only — +/// the output is still a valid set of levels any decoder reconstructs. +/// +/// NOTE: not wired into the encoder by default. Greedy per-coefficient rounding +/// fights the intra-prediction feedback loop (rounding one block down worsens +/// the next block's prediction), so a net win needs a feedback-aware integration +/// — left as future work. Kept here as a verified building block. +pub fn trellis_quant(coeffs: &[i32; 16], qp: u8, intra: bool, lambda: f64) -> [i32; 16] { + let m = (qp % 6) as usize; + let qbits = 15 + (qp / 6) as u32; + let scale = (1u64 << qbits) as f64; + let off: i64 = if intra { (1i64 << qbits) / 3 } else { (1i64 << qbits) / 6 }; + let mut out = [0i32; 16]; + for i in 0..4 { + for j in 0..4 { + let idx = i * 4 + j; + let w = coeffs[idx] as i64; + let mf = QUANT_MF[m][pos_group(i, j)] as i64; + let num = w.abs() * mf; // == ideal_level * 2^qbits + let l_scalar = (num + off) >> qbits; + if l_scalar == 0 { + continue; + } + // Distortion is in level² units; convert λ (pixel-SSD) into that + // domain via the dequant step (step ≈ 2^qbits / mf, pixel ≈ step/8). + let lambda_q = lambda * (mf * mf) as f64 / (scale * scale) * 64.0; + let ideal = num as f64 / scale; + let mut best = l_scalar; + let mut best_j = f64::MAX; + for cand in [l_scalar - 1, l_scalar] { + let d = (ideal - cand as f64).powi(2); + let r = if cand == 0 { + 0.0 + } else { + // ~bits to code |level|: significance + sign + magnitude. + 2.0 + 2.0 * (64 - (cand as u64).leading_zeros()) as f64 + }; + let jj = d + lambda_q * r; + if jj < best_j { + best_j = jj; + best = cand; + } + } + out[idx] = if w < 0 { -best as i32 } else { best as i32 }; + } + } + out +} + +/// Dequantizes levels to scaled coefficients (spec §8.5.12.1, flat scaling +/// list so `LevelScale = 16 · normAdjust`). +/// OPT-IN SWITCH — `RS_H264_DEQUANT_AVX2=1` enables the AVX2 twin, which measured NULL +/// (8/13 favouring scalar, z = 0.83). Both arms live in one binary so the A/B runs under +/// one thermal state; separate builds cannot resolve an effect this size here. +#[cfg(all(target_arch = "x86_64", feature = "asm"))] +#[inline] +fn dequant_avx2_opt_in() -> bool { + use std::sync::atomic::{AtomicU8, Ordering}; + static ON: AtomicU8 = AtomicU8::new(0); + match ON.load(Ordering::Relaxed) { + 1 => true, + 2 => false, + _ => { + let on = std::env::var_os("RS_H264_DEQUANT_AVX2").is_some_and(|v| v != "0"); + ON.store(if on { 1 } else { 2 }, Ordering::Relaxed); + on + } + } +} + +pub fn dequantize(levels: &[i32; 16], qp: u8) -> [i32; 16] { + let _g = crate::prof::scope(crate::prof::Stage::Dequant); + let m = (qp % 6) as usize; + let shift = (qp / 6) as i32; + let ls = &LEVEL_SCALE_FLAT[m]; + let mut out = [0i32; 16]; + // AVX2 twin: 16 scalar `imul` -> 2 `vpmulld`. Bit-identical (exact integer ops in + // the same order), so the scalar body below stays as the oracle AND as the path on + // any non-AVX2 CPU. See `dequant_4x4_avx2` for why auto-vectorization does not + // reach this loop. + // DEFAULT: SCALAR. The AVX2 twin is opt-IN (`RS_H264_DEQUANT_AVX2=1`). + // + // MEASURED NULL, leaning negative: 13 pairs, pinned, CPU time, ABBA, against a null + // arm of 0.989 taken in the same session — the SCALAR arm was faster in 8/13 + // (z = 0.83, not significant either way). The kernel provably removes 8x the + // multiply instructions (776M `imul` -> 97M `vpmulld`, confirmed in the asm) and + // that bought NOTHING. + // + // Why: dequant loads 16 levels + 16 scale factors and stores 16 outputs — 192 bytes + // per call. It is MEMORY-bound, so the scalar `imul`s were already hidden under the + // loads. Widening the arithmetic cannot help a loop whose clock is set by traffic. + // This is the same law that reverted three earlier bricks in this campaign: a + // counter proves work was REMOVED, never that time was SAVED. + // + // Kept in tree (byte-identical, bit-exact-gated) because it costs nothing to keep + // and re-testing is one env var if the surrounding loads ever shrink. + #[cfg(all(target_arch = "x86_64", feature = "asm"))] + if dequant_avx2_opt_in() && rusty_h264_accel::dequant_4x4(&mut out, levels, ls, qp) { + return out; + } + if qp >= 24 { + let sh = shift - 4; + for idx in 0..16 { + out[idx] = (levels[idx] * ls[idx]) << sh; + } + } else { + let add = 1 << (3 - shift); + let sh = 4 - shift; + for idx in 0..16 { + out[idx] = (levels[idx] * ls[idx] + add) >> sh; + } + } + out +} + +/// 4×4 zig-zag: scan position → raster position (spec Table 8-13; the inverse +/// of the `un_scan_4x4_dcac` mapping in `cavlc.rs`). +pub const ZIG4: [usize; 16] = [0, 1, 4, 8, 5, 2, 3, 6, 9, 12, 13, 10, 7, 11, 14, 15]; + +/// Fused un-scan + dequant that touches ONLY the significant coefficients. +/// +/// Bit-exact with `dequantize(&un_scan(scan))` / the weighted twin: a zero +/// level dequantizes to zero under both branches (for qp<24, +/// `(0·ls + (1<<(3-shift))) >> (4-shift)` is 0 for every shift 0..=3), so +/// skipping the zeros IS the dense computation. `nnz` is the parse's count of +/// significant coefficients (exact — CABAC levels are never zero), so the loop +/// exits after the LAST significant coefficient instead of walking all 16: +/// dense un-scan (16 loads+stores) + dense dequant (16 multiplies) become +/// `nnz` multiplies scattered directly to raster order. +/// +/// `ac_shift` selects the category's scan base: 0 for a full DC+AC block, +/// 1 for an AC-only block (chroma AC), whose scan index `i` is overall scan +/// position `i + 1`. +#[inline] +pub fn dequant_scatter_4x4( + scan: &[i32; 16], + nnz: u8, + ac_shift: usize, + qp: u8, + weight: Option<&[i32; 16]>, +) -> [i32; 16] { + let _g = crate::prof::scope(crate::prof::Stage::Dequant); + let m = (qp % 6) as usize; + let shift = (qp / 6) as i32; + let mut out = [0i32; 16]; + let mut seen = 0u8; + let mut i = 0usize; + while seen < nnz && i + ac_shift < 16 { + let v = scan[i]; + if v != 0 { + let pos = ZIG4[i + ac_shift]; + let ls = match weight { + Some(w) => w[pos] * NORM_ADJUST[m][POS_GROUP_FLAT[pos]], + None => LEVEL_SCALE_FLAT[m][pos], + }; + out[pos] = if qp >= 24 { + (v * ls) << (shift - 4) + } else { + (v * ls + (1 << (3 - shift))) >> (4 - shift) + }; + seen += 1; + } + i += 1; + } + out +} + +/// Dequantizes ONLY position 0 of a 4×4 block — the single-coefficient twin of +/// [`dequantize`] / [`dequantize_weighted`], bit-exact with their `out[0]`. +/// +/// Exists for the DC-ONLY fast path: when a block's sole significant +/// coefficient is the DC, `inverse_core` provably flattens to `(f + 32) >> 6` +/// at every position (row pass spreads f across row 0, column pass across all +/// rows, and each `inv_1d` of `(f,0,0,0)` is exact — no `>> 1` flooring path is +/// taken), so the full 16-multiply dequant + two butterfly passes reduce to +/// this one multiply. This is ffmpeg's `h264_idct_dc_add` split, arrived at +/// from the fusion diagnosis (WHYS Part 8). +#[inline] +pub fn dequantize_dc4(level: i32, qp: u8, weight0: Option) -> i32 { + let m = (qp % 6) as usize; + let shift = (qp / 6) as i32; + let ls0 = match weight0 { + Some(w) => w * NORM_ADJUST[m][POS_GROUP_FLAT[0]], + None => LEVEL_SCALE_FLAT[m][0], + }; + if qp >= 24 { + (level * ls0) << (shift - 4) + } else { + (level * ls0 + (1 << (3 - shift))) >> (4 - shift) + } +} + +/// Dequantizes with a per-position weight scale (`weightScale4x4` in raster order, +/// `16` = flat) — High-profile scaling matrices (spec §8.5.12.1, +/// `LevelScale = weightScale · normAdjust`). +pub fn dequantize_weighted(levels: &[i32; 16], qp: u8, weight: &[i32; 16]) -> [i32; 16] { + let _g = crate::prof::scope(crate::prof::Stage::Dequant); + let m = (qp % 6) as usize; + let shift = (qp / 6) as i32; + let ls: [i32; 16] = std::array::from_fn(|idx| weight[idx] * NORM_ADJUST[m][POS_GROUP_FLAT[idx]]); + let mut out = [0i32; 16]; + if qp >= 24 { + let sh = shift - 4; + for idx in 0..16 { + out[idx] = (levels[idx] * ls[idx]) << sh; + } + } else { + let add = 1 << (3 - shift); + let sh = 4 - shift; + for idx in 0..16 { + out[idx] = (levels[idx] * ls[idx] + add) >> sh; + } + } + out +} + +/// Inverse core transform + final normalization, turning dequantized +/// coefficients back into a residual block (spec §8.5.12.2: `(f + 32) >> 6`). +pub fn inverse_core(coeffs: &[i32; 16]) -> [i32; 16] { + let mut m = *coeffs; + // Rows first, then columns. The order is **not** interchangeable: the + // `>> 1` flooring inside `inv_1d` makes the integer transform non-separable, + // so the spec (§8.5.12.2 — horizontal row transform, then vertical) and the + // decoder must agree exactly. (A column-first pass diverges by ±1 on + // asymmetric blocks, which only surfaces at low QP / high-frequency content.) + for r in 0..4 { + let (a, b, c, d) = inv_1d(m[r * 4], m[r * 4 + 1], m[r * 4 + 2], m[r * 4 + 3]); + m[r * 4] = a; + m[r * 4 + 1] = b; + m[r * 4 + 2] = c; + m[r * 4 + 3] = d; + } + for c in 0..4 { + let (a, b, cc, d) = inv_1d(m[c], m[4 + c], m[8 + c], m[12 + c]); + m[c] = a; + m[4 + c] = b; + m[8 + c] = cc; + m[12 + c] = d; + } + for v in m.iter_mut() { + *v = (*v + 32) >> 6; + } + m +} + +/// Convenience: full forward path, residual → quantized levels (default +/// dead-zones: 3 for intra, 6 for inter). +pub fn forward_quant(residual: &[i32; 16], qp: u8, intra: bool) -> [i32; 16] { + quantize(&forward_core(residual), qp, if intra { 3 } else { 6 }) +} + +/// Convenience: full inverse path, quantized levels → reconstructed residual. +pub fn inverse_quant(levels: &[i32; 16], qp: u8) -> [i32; 16] { + inverse_core(&dequantize(levels, qp)) +} + +// ---- 8×8 transform (High profile, spec §8.5.13) ---- + +/// `normAdjust8x8` (spec Table 8-15), indexed by `[QP % 6]` then 8×8 position +/// group (see [`pos_group_8x8`]). +const NORM_ADJUST_8X8: [[i32; 6]; 6] = [ + [20, 18, 32, 19, 25, 24], + [22, 19, 35, 21, 28, 26], + [26, 23, 42, 24, 33, 31], + [28, 25, 45, 26, 35, 33], + [32, 28, 51, 30, 40, 38], + [36, 32, 58, 34, 46, 43], +]; + +/// Position group of `(i, j)` within an 8×8 block (spec §8.5.13.1) — six groups +/// vs the 4×4's three. +#[inline] +const fn pos_group_8x8(i: usize, j: usize) -> usize { + let (i4, j4) = (i % 4, j % 4); + if i4 == 0 && j4 == 0 { + 0 + } else if i % 2 == 1 && j % 2 == 1 { + 1 + } else if i4 == 2 && j4 == 2 { + 2 + } else if (i4 == 0 && j % 2 == 1) || (i % 2 == 1 && j4 == 0) { + 3 + } else if (i4 == 0 && j4 == 2) || (i4 == 2 && j4 == 0) { + 4 + } else { + 5 + } +} + +/// `pos_group_8x8` flattened over the 64 raster positions. +const POS_GROUP_8X8_FLAT: [usize; 64] = { + let mut out = [0usize; 64]; + let mut i = 0; + while i < 8 { + let mut j = 0; + while j < 8 { + out[i * 8 + j] = pos_group_8x8(i, j); + j += 1; + } + i += 1; + } + out +}; + +/// One-dimensional inverse 8×8 transform (spec §8.5.13.2 butterfly). +#[inline] +fn inv_1d_8x8(d: &[i32; 8]) -> [i32; 8] { + let a0 = d[0] + d[4]; + let a4 = d[0] - d[4]; + let a2 = (d[2] >> 1) - d[6]; + let a6 = d[2] + (d[6] >> 1); + let b0 = a0 + a6; + let b2 = a4 + a2; + let b4 = a4 - a2; + let b6 = a0 - a6; + let a1 = -d[3] + d[5] - d[7] - (d[7] >> 1); + let a3 = d[1] + d[7] - d[3] - (d[3] >> 1); + let a5 = -d[1] + d[7] + d[5] + (d[5] >> 1); + let a7 = d[3] + d[5] + d[1] + (d[1] >> 1); + let b1 = a1 + (a7 >> 2); + let b7 = a7 - (a1 >> 2); + let b3 = a3 + (a5 >> 2); + let b5 = (a3 >> 2) - a5; + [b0 + b7, b2 + b5, b4 + b3, b6 + b1, b6 - b1, b4 - b3, b2 - b5, b0 - b7] +} + +/// One-dimensional forward 8×8 transform — the matched pair of [`inv_1d_8x8`] +/// (the ENCODER's forward transform for the High-profile 8×8 residual). +#[inline] +fn fwd_1d_8x8(s: &[i32; 8]) -> [i32; 8] { + let a0 = s[0] + s[7]; + let a1 = s[1] + s[6]; + let a2 = s[2] + s[5]; + let a3 = s[3] + s[4]; + let a4 = s[0] - s[7]; + let a5 = s[1] - s[6]; + let a6 = s[2] - s[5]; + let a7 = s[3] - s[4]; + let b0 = a0 + a3; + let b1 = a1 + a2; + let b2 = a0 - a3; + let b3 = a1 - a2; + let y0 = b0 + b1; + let y2 = b2 + (b3 >> 1); + let y4 = b0 - b1; + let y6 = (b2 >> 1) - b3; + let b4 = a5 + a6 + ((a4 >> 1) + a4); + let b5 = a4 - a7 - ((a6 >> 1) + a6); + let b6 = a4 + a7 - ((a5 >> 1) + a5); + let b7 = a5 - a6 + ((a7 >> 1) + a7); + let y1 = b4 + (b7 >> 2); + let y3 = b5 + (b6 >> 2); + let y5 = b6 - (b5 >> 2); + let y7 = (b4 >> 2) - b7; + [y0, y1, y2, y3, y4, y5, y6, y7] +} + +/// Inverse 8×8 core transform + normalization (`(x + 32) >> 6`), rows then +/// columns (non-separable, like the 4×4 — the order is fixed by the spec). +pub fn inverse_core_8x8(coeffs: &[i32; 64]) -> [i32; 64] { + let _g = crate::prof::scope(crate::prof::Stage::Reconstruct); + let mut m = *coeffs; + for r in 0..8 { + let row: [i32; 8] = std::array::from_fn(|k| m[r * 8 + k]); + let o = inv_1d_8x8(&row); + for k in 0..8 { + m[r * 8 + k] = o[k]; + } + } + for c in 0..8 { + let col: [i32; 8] = std::array::from_fn(|k| m[k * 8 + c]); + let o = inv_1d_8x8(&col); + for k in 0..8 { + m[k * 8 + c] = o[k]; + } + } + for v in m.iter_mut() { + *v = (*v + 32) >> 6; + } + m +} + +/// Forward 8×8 core transform (rows then columns) — the encoder counterpart of +/// [`inverse_core_8x8`]. Output are un-normalized transform coefficients for +/// [`quantize_8x8`]; the normalization lives in the quant/dequant scale. +pub fn forward_core_8x8(res: &[i32; 64]) -> [i32; 64] { + let mut m = *res; + for r in 0..8 { + let row: [i32; 8] = std::array::from_fn(|k| m[r * 8 + k]); + let o = fwd_1d_8x8(&row); + for k in 0..8 { + m[r * 8 + k] = o[k]; + } + } + for c in 0..8 { + let col: [i32; 8] = std::array::from_fn(|k| m[k * 8 + c]); + let o = fwd_1d_8x8(&col); + for k in 0..8 { + m[k * 8 + c] = o[k]; + } + } + m +} + +/// Dequantizes an 8×8 block (spec §8.5.13.1) with a per-position `weight` scale +/// (raster order, `16` = flat). `LevelScale8x8 = weight · normAdjust8x8`. +pub fn dequantize_8x8(levels: &[i32; 64], qp: u8, weight: &[i32; 64]) -> [i32; 64] { + let _g = crate::prof::scope(crate::prof::Stage::Dequant); + let m = (qp % 6) as usize; + let shift = (qp / 6) as i32; + let mut out = [0i32; 64]; + if qp >= 36 { + let sh = shift - 6; + for idx in 0..64 { + let ls = weight[idx] * NORM_ADJUST_8X8[m][POS_GROUP_8X8_FLAT[idx]]; + out[idx] = (levels[idx] * ls) << sh; + } + } else { + let add = 1 << (5 - shift); + let sh = 6 - shift; + for idx in 0..64 { + let ls = weight[idx] * NORM_ADJUST_8X8[m][POS_GROUP_8X8_FLAT[idx]]; + out[idx] = (levels[idx] * ls + add) >> sh; + } + } + out +} + +/// Convenience: full inverse 8×8 path, levels → reconstructed residual. +pub fn inverse_quant_8x8(levels: &[i32; 64], qp: u8, weight: &[i32; 64]) -> [i32; 64] { + inverse_core_8x8(&dequantize_8x8(levels, qp, weight)) +} + +/// 8×8 forward-quant multiplier `MF = round(2^18 / normAdjust8x8)` per `[QP%6]` +/// then position group. Chosen as the exact arithmetic inverse of +/// [`dequantize_8x8`]'s scale (`MF · weight · normAdjust ≈ 2^qbits`, qbits = +/// 16+QP/6, flat weight 16) so quant∘dequant round-trips near-identity. +const QUANT_MF_8X8: [[i32; 6]; 6] = [ + [13107, 14564, 8192, 13797, 10486, 10923], + [11916, 13797, 7490, 12483, 9362, 10083], + [10083, 11398, 6242, 10923, 7944, 8456], + [9362, 10486, 5825, 10083, 7490, 7944], + [8192, 9362, 5140, 8738, 6554, 6899], + [7282, 8192, 4520, 7710, 5699, 6096], +]; + +/// Forward-quantizes an 8×8 coefficient block (encoder). `level = (|c|·MF + F) >> +/// qbits`, qbits = 16+QP/6, deadzone `F = 2^qbits / dz_div` (like the 4×4 path). +/// `weight` is the per-position scaling-list value (raster; `16` = flat) — the +/// matched inverse of [`dequantize_8x8`], so `dequantize_8x8(quantize_8x8(c)) ≈ c`. +pub fn quantize_8x8(coeffs: &[i32; 64], qp: u8, weight: &[i32; 64], dz_div: i64) -> [i32; 64] { + let m = (qp % 6) as usize; + let qbits = 16 + (qp / 6) as i64; + let ff = (1i64 << qbits) / dz_div; + let mut out = [0i32; 64]; + for idx in 0..64 { + let mf = QUANT_MF_8X8[m][POS_GROUP_8X8_FLAT[idx]] as i64 * 16 / weight[idx] as i64; + let a = coeffs[idx].unsigned_abs() as i64; + let lvl = ((a * mf + ff) >> qbits) as i32; + out[idx] = if coeffs[idx] < 0 { -lvl } else { lvl }; + } + out +} + +// ---- Secondary DC transforms for I_16x16 luma and chroma (Hadamard) ---- + +/// In-place 1D 4-point Hadamard (its own inverse up to scale). +#[inline] +fn hadamard_1d(a: i32, b: i32, c: i32, d: i32) -> (i32, i32, i32, i32) { + (a + b + c + d, a + b - c - d, a - b - c + d, a - b + c - d) +} + +/// 4×4 Hadamard transform (rows then columns), used for the I_16x16 luma DC +/// block. Symmetric, so the same routine serves forward and inverse. +pub fn hadamard_4x4(block: &[i32; 16]) -> [i32; 16] { + let mut m = *block; + for r in 0..4 { + let (a, b, c, d) = hadamard_1d(m[r * 4], m[r * 4 + 1], m[r * 4 + 2], m[r * 4 + 3]); + m[r * 4] = a; + m[r * 4 + 1] = b; + m[r * 4 + 2] = c; + m[r * 4 + 3] = d; + } + for c in 0..4 { + let (a, b, cc, d) = hadamard_1d(m[c], m[4 + c], m[8 + c], m[12 + c]); + m[c] = a; + m[4 + c] = b; + m[8 + c] = cc; + m[12 + c] = d; + } + m +} + +/// 4-point Hadamard butterfly applied lane-wise across four SIMD vectors. Same +/// `(a+b+c+d, a+b-c-d, a-b-c+d, a-b+c-d)` as the scalar [`hadamard_1d`]. +#[inline] +fn had4_simd( + a: wide::i32x4, + b: wide::i32x4, + c: wide::i32x4, + d: wide::i32x4, +) -> (wide::i32x4, wide::i32x4, wide::i32x4, wide::i32x4) { + (a + b + c + d, a + b - c - d, a - b - c + d, a - b + c - d) +} + +/// SATD of exactly four 4×4 residual blocks at once, summed. Each block lives in +/// its own SIMD lane, so the position-within-block dimension runs across the +/// array of vectors — both Hadamard passes become plain across-vector butterflies +/// with no transpose. Bit-identical to summing `Σ|hadamard_4x4(res)|` per block. +fn satd_4x4_x4(b: [&[i32; 16]; 4]) -> i64 { + use wide::i32x4; + // v[p] holds position `p` of all four blocks (lane k = block k). + let mut v = [i32x4::from([0i32; 4]); 16]; + for (p, slot) in v.iter_mut().enumerate() { + *slot = i32x4::from([b[0][p], b[1][p], b[2][p], b[3][p]]); + } + // Row transform: combine the four positions within each row. + for r in 0..4 { + let i = r * 4; + let (a, c, d, e) = had4_simd(v[i], v[i + 1], v[i + 2], v[i + 3]); + (v[i], v[i + 1], v[i + 2], v[i + 3]) = (a, c, d, e); + } + // Column transform: combine the four rows at each column. + for c in 0..4 { + let (a, b2, d, e) = had4_simd(v[c], v[c + 4], v[c + 8], v[c + 12]); + (v[c], v[c + 4], v[c + 8], v[c + 12]) = (a, b2, d, e); + } + // Σ|coeff|, lane-wise (|x| = max(0,x) − min(0,x)), then sum the four lanes. + let zero = i32x4::from([0i32; 4]); + let mut acc = zero; + for x in v { + acc += zero.max(x) - zero.min(x); + } + acc.to_array().iter().map(|&s| s as i64).sum() +} + +/// SATD over a slice of 4×4 residual blocks (SIMD four at a time, scalar tail). +/// This is the cost kernel for motion estimation and RD mode decision. +pub fn satd_4x4_sum(blocks: &[[i32; 16]]) -> i64 { + let mut total = 0i64; + let mut chunks = blocks.chunks_exact(4); + for g in &mut chunks { + total += satd_4x4_x4([&g[0], &g[1], &g[2], &g[3]]); + } + for res in chunks.remainder() { + total += hadamard_4x4(res).iter().map(|&v| v.unsigned_abs() as i64).sum::(); + } + total +} + +/// Forward core 1-D butterfly applied lane-wise across four SIMD vectors. Same +/// `(t0+t1, 2·t3+t2, t0-t1, t3-2·t2)` as the scalar [`fwd_1d`]. +#[inline] +fn fwd_1d_simd( + x0: wide::i32x4, + x1: wide::i32x4, + x2: wide::i32x4, + x3: wide::i32x4, +) -> (wide::i32x4, wide::i32x4, wide::i32x4, wide::i32x4) { + let t0 = x0 + x3; + let t1 = x1 + x2; + let t2 = x1 - x2; + let t3 = x0 - x3; + (t0 + t1, (t3 + t3) + t2, t0 - t1, t3 - (t2 + t2)) +} + +/// Forward core 4×4 transform of four blocks at once — each block in its own SIMD +/// lane, so both passes are across-vector butterflies (no transpose), exactly like +/// [`satd_4x4_sum`]. Integer math ⇒ bit-identical to four [`forward_core`] calls. +fn forward_core_x4(b: [&[i32; 16]; 4]) -> [[i32; 16]; 4] { + use wide::i32x4; + let mut v = [i32x4::from([0i32; 4]); 16]; + for (p, slot) in v.iter_mut().enumerate() { + *slot = i32x4::from([b[0][p], b[1][p], b[2][p], b[3][p]]); + } + for r in 0..4 { + let i = r * 4; + let (a, c, d, e) = fwd_1d_simd(v[i], v[i + 1], v[i + 2], v[i + 3]); + (v[i], v[i + 1], v[i + 2], v[i + 3]) = (a, c, d, e); + } + for c in 0..4 { + let (a, b2, d, e) = fwd_1d_simd(v[c], v[c + 4], v[c + 8], v[c + 12]); + (v[c], v[c + 4], v[c + 8], v[c + 12]) = (a, b2, d, e); + } + let mut out = [[0i32; 16]; 4]; + for (p, vp) in v.iter().enumerate() { + let a = vp.to_array(); + for k in 0..4 { + out[k][p] = a[k]; + } + } + out +} + +/// `i32x8` (AVX2-width, 8 blocks/lane) sibling of [`fwd_1d_simd`] — mirrors the +/// width of x264's AVX2 DCT kernels. (Realizes AVX2 only under a CPU-targeted +/// build/dispatch; on the portable SSE2 build it is two `i32x4` ops.) +#[inline] +fn fwd_1d_simd8( + x0: wide::i32x8, + x1: wide::i32x8, + x2: wide::i32x8, + x3: wide::i32x8, +) -> (wide::i32x8, wide::i32x8, wide::i32x8, wide::i32x8) { + let t0 = x0 + x3; + let t1 = x1 + x2; + let t2 = x1 - x2; + let t3 = x0 - x3; + (t0 + t1, (t3 + t3) + t2, t0 - t1, t3 - (t2 + t2)) +} + +/// Forward core 4×4 transform of EIGHT blocks at once (8-wide `i32x8`, AVX2 +/// kernel width). Bit-identical to eight [`forward_core`] calls. +fn forward_core_x8(b: [&[i32; 16]; 8]) -> [[i32; 16]; 8] { + use wide::i32x8; + let mut v = [i32x8::from([0i32; 8]); 16]; + for (p, slot) in v.iter_mut().enumerate() { + *slot = i32x8::from([ + b[0][p], b[1][p], b[2][p], b[3][p], b[4][p], b[5][p], b[6][p], b[7][p], + ]); + } + for r in 0..4 { + let i = r * 4; + let (a, c, d, e) = fwd_1d_simd8(v[i], v[i + 1], v[i + 2], v[i + 3]); + (v[i], v[i + 1], v[i + 2], v[i + 3]) = (a, c, d, e); + } + for c in 0..4 { + let (a, b2, d, e) = fwd_1d_simd8(v[c], v[c + 4], v[c + 8], v[c + 12]); + (v[c], v[c + 4], v[c + 8], v[c + 12]) = (a, b2, d, e); + } + let mut out = [[0i32; 16]; 8]; + for (p, vp) in v.iter().enumerate() { + let a = vp.to_array(); + for k in 0..8 { + out[k][p] = a[k]; + } + } + out +} + +/// Forward core transform over a batch of 4×4 residual blocks — the encoder's +/// whole-macroblock DCT, mirroring x264's `sub16x16_dct`. SIMD eight at a time +/// (`i32x8`, AVX2 width), then four (`i32x4`), then a scalar tail. +pub fn forward_dct_blocks(res: &[[i32; 16]], out: &mut [[i32; 16]]) { + let mut i = 0; + let mut c8 = res.chunks_exact(8); + for g in &mut c8 { + let r = forward_core_x8([&g[0], &g[1], &g[2], &g[3], &g[4], &g[5], &g[6], &g[7]]); + out[i..i + 8].clone_from_slice(&r); + i += 8; + } + let mut c4 = c8.remainder().chunks_exact(4); + for g in &mut c4 { + let r = forward_core_x4([&g[0], &g[1], &g[2], &g[3]]); + out[i..i + 4].clone_from_slice(&r); + i += 4; + } + for r in c4.remainder() { + out[i] = forward_core(r); + i += 1; + } +} + +/// Inverse core 1-D butterfly applied lane-wise across four SIMD vectors. Same +/// `(e0+e3, e1+e2, e1-e2, e0-e3)` as the scalar [`inv_1d`] (per-lane arithmetic +/// `>> 1`, so bit-identical). +#[inline] +fn inv_1d_simd( + d0: wide::i32x4, + d1: wide::i32x4, + d2: wide::i32x4, + d3: wide::i32x4, +) -> (wide::i32x4, wide::i32x4, wide::i32x4, wide::i32x4) { + let e0 = d0 + d2; + let e1 = d0 - d2; + let e2 = (d1 >> 1) - d3; + let e3 = d1 + (d3 >> 1); + (e0 + e3, e1 + e2, e1 - e2, e0 - e3) +} + +/// Inverse core 4×4 transform + `(f + 32) >> 6` normalization of four blocks at +/// once — each block in its own SIMD lane. Bit-identical to four [`inverse_core`]. +fn inverse_core_x4(b: [&[i32; 16]; 4]) -> [[i32; 16]; 4] { + use wide::i32x4; + let mut v = [i32x4::from([0i32; 4]); 16]; + for (p, slot) in v.iter_mut().enumerate() { + *slot = i32x4::from([b[0][p], b[1][p], b[2][p], b[3][p]]); + } + for r in 0..4 { + let i = r * 4; + let (a, c, d, e) = inv_1d_simd(v[i], v[i + 1], v[i + 2], v[i + 3]); + (v[i], v[i + 1], v[i + 2], v[i + 3]) = (a, c, d, e); + } + for c in 0..4 { + let (a, b2, d, e) = inv_1d_simd(v[c], v[c + 4], v[c + 8], v[c + 12]); + (v[c], v[c + 4], v[c + 8], v[c + 12]) = (a, b2, d, e); + } + let off = i32x4::from([32i32; 4]); + for vp in v.iter_mut() { + *vp = (*vp + off) >> 6; + } + let mut out = [[0i32; 16]; 4]; + for (p, vp) in v.iter().enumerate() { + let a = vp.to_array(); + for k in 0..4 { + out[k][p] = a[k]; + } + } + out +} + +/// `i32x8` (AVX2-width) sibling of [`inv_1d_simd`]. +#[inline] +fn inv_1d_simd8( + d0: wide::i32x8, + d1: wide::i32x8, + d2: wide::i32x8, + d3: wide::i32x8, +) -> (wide::i32x8, wide::i32x8, wide::i32x8, wide::i32x8) { + let e0 = d0 + d2; + let e1 = d0 - d2; + let e2 = (d1 >> 1) - d3; + let e3 = d1 + (d3 >> 1); + (e0 + e3, e1 + e2, e1 - e2, e0 - e3) +} + +/// Inverse core 4×4 transform + normalization of EIGHT blocks at once (`i32x8`). +/// Bit-identical to eight [`inverse_core`] calls. +fn inverse_core_x8(b: [&[i32; 16]; 8]) -> [[i32; 16]; 8] { + use wide::i32x8; + let mut v = [i32x8::from([0i32; 8]); 16]; + for (p, slot) in v.iter_mut().enumerate() { + *slot = i32x8::from([ + b[0][p], b[1][p], b[2][p], b[3][p], b[4][p], b[5][p], b[6][p], b[7][p], + ]); + } + for r in 0..4 { + let i = r * 4; + let (a, c, d, e) = inv_1d_simd8(v[i], v[i + 1], v[i + 2], v[i + 3]); + (v[i], v[i + 1], v[i + 2], v[i + 3]) = (a, c, d, e); + } + for c in 0..4 { + let (a, b2, d, e) = inv_1d_simd8(v[c], v[c + 4], v[c + 8], v[c + 12]); + (v[c], v[c + 4], v[c + 8], v[c + 12]) = (a, b2, d, e); + } + let off = i32x8::from([32i32; 8]); + for vp in v.iter_mut() { + *vp = (*vp + off) >> 6; + } + let mut out = [[0i32; 16]; 8]; + for (p, vp) in v.iter().enumerate() { + let a = vp.to_array(); + for k in 0..8 { + out[k][p] = a[k]; + } + } + out +} + +/// Inverse core transform + normalization over a batch of dequantized 4×4 blocks +/// — the whole-macroblock IDCT, mirroring x264's `add16x16_idct`. SIMD eight at a +/// time (`i32x8`), then four (`i32x4`), then a scalar tail. Bit-identical to +/// [`inverse_core`] per block. (Add-prediction + clip stays per-block at the call +/// site, where the prediction layout lives.) +pub fn inverse_dct_blocks(coeffs: &[[i32; 16]], out: &mut [[i32; 16]]) { + let mut i = 0; + let mut c8 = coeffs.chunks_exact(8); + for g in &mut c8 { + let r = inverse_core_x8([&g[0], &g[1], &g[2], &g[3], &g[4], &g[5], &g[6], &g[7]]); + out[i..i + 8].clone_from_slice(&r); + i += 8; + } + let mut c4 = c8.remainder().chunks_exact(4); + for g in &mut c4 { + let r = inverse_core_x4([&g[0], &g[1], &g[2], &g[3]]); + out[i..i + 4].clone_from_slice(&r); + i += 4; + } + for r in c4.remainder() { + out[i] = inverse_core(r); + i += 1; + } +} + + +/// Forward transform + quantization of the 16 luma DC coefficients of an +/// I_16x16 macroblock (spec §8.5.10). Input/output are row-major 4×4. +pub fn forward_quant_luma_dc(dc: &[i32; 16], qp: u8, intra: bool) -> [i32; 16] { + let f = hadamard_4x4(dc); + let m = (qp % 6) as usize; + // The 4×4 Hadamard has gain 16 (its square is 16·I), so the luma DC quant + // carries two extra bits over the AC quant to keep the reconstructed DC at + // the same scale as the regular dequantized DC coefficient. + let qbits = 17 + (qp / 6) as u32; + let off: i64 = if intra { (1i64 << qbits) / 3 } else { (1i64 << qbits) / 6 }; + let mf = QUANT_MF[m][0] as i64; + let mut out = [0i32; 16]; + for (o, &fv) in out.iter_mut().zip(f.iter()) { + let level = ((fv.abs() as i64) * mf + off) >> qbits; + *o = if fv < 0 { -level as i32 } else { level as i32 }; + } + out +} + +/// Inverse quantization + transform of the I_16x16 luma DC block, returning the +/// reconstructed DC values to scatter into each 4×4 luma block (spec §8.5.10). +pub fn inverse_quant_luma_dc(levels: &[i32; 16], qp: u8) -> [i32; 16] { + let _g = crate::prof::scope(crate::prof::Stage::Dequant); + let g = hadamard_4x4(levels); + let m = (qp % 6) as usize; + let shift = (qp / 6) as i32; + let level_scale = 16 * NORM_ADJUST[m][0]; + let mut out = [0i32; 16]; + for (o, &gv) in out.iter_mut().zip(g.iter()) { + *o = if qp >= 36 { + (gv * level_scale) << (shift - 6) + } else { + (gv * level_scale + (1 << (5 - shift))) >> (6 - shift) + }; + } + out +} + +/// `inverse_quant_luma_dc` with the scaling matrix's DC weight (`w00`, the +/// raster (0,0) entry; `16` = flat). +pub fn inverse_quant_luma_dc_weighted(levels: &[i32; 16], qp: u8, w00: i32) -> [i32; 16] { + let g = hadamard_4x4(levels); + let m = (qp % 6) as usize; + let shift = (qp / 6) as i32; + let level_scale = w00 * NORM_ADJUST[m][0]; + let mut out = [0i32; 16]; + for (o, &gv) in out.iter_mut().zip(g.iter()) { + *o = if qp >= 36 { + (gv * level_scale) << (shift - 6) + } else { + (gv * level_scale + (1 << (5 - shift))) >> (6 - shift) + }; + } + out +} + +/// `inverse_quant_chroma_dc` with the scaling matrix's DC weight. +pub fn inverse_quant_chroma_dc_weighted(levels: &[i32; 4], qp: u8, w00: i32) -> [i32; 4] { + let g = hadamard_2x2(levels); + let m = (qp % 6) as usize; + let shift = (qp / 6) as i32; + let level_scale = w00 * NORM_ADJUST[m][0]; + let mut out = [0i32; 4]; + for (o, &gv) in out.iter_mut().zip(g.iter()) { + *o = ((gv * level_scale) << shift) >> 5; + } + out +} + +/// 2×2 Hadamard for a chroma DC block (its own inverse up to scale). +pub fn hadamard_2x2(dc: &[i32; 4]) -> [i32; 4] { + let (a, b, c, d) = (dc[0], dc[1], dc[2], dc[3]); + [a + b + c + d, a - b + c - d, a + b - c - d, a - b - c + d] +} + +/// Forward transform + quantization of a chroma DC block (4 coeffs, spec §8.5.11). +pub fn forward_quant_chroma_dc(dc: &[i32; 4], qp: u8, intra: bool) -> [i32; 4] { + let f = hadamard_2x2(dc); + let m = (qp % 6) as usize; + let qbits = 15 + (qp / 6) as u32; + let off: i64 = if intra { (1i64 << qbits) / 3 } else { (1i64 << qbits) / 6 }; + let mf = QUANT_MF[m][0] as i64; + let mut out = [0i32; 4]; + for (o, &fv) in out.iter_mut().zip(f.iter()) { + let level = ((fv.abs() as i64) * mf + 2 * off) >> (qbits + 1); + *o = if fv < 0 { -level as i32 } else { level as i32 }; + } + out +} + +/// Inverse quantization + transform of a chroma DC block (spec §8.5.11.2). +pub fn inverse_quant_chroma_dc(levels: &[i32; 4], qp: u8) -> [i32; 4] { + let _g = crate::prof::scope(crate::prof::Stage::Dequant); + let g = hadamard_2x2(levels); + let m = (qp % 6) as usize; + let shift = (qp / 6) as i32; + let level_scale = 16 * NORM_ADJUST[m][0]; + let mut out = [0i32; 4]; + for (o, &gv) in out.iter_mut().zip(g.iter()) { + *o = ((gv * level_scale) << shift) >> 5; + } + out +} + +#[cfg(test)] +mod tests { + use super::*; + + /// The AVX2 dequant twin must be BIT-IDENTICAL to the scalar oracle — these are + /// exact integer ops, so this is `assert_eq!`, not a tolerance. + /// + /// Sweeps the FULL qp range 0..=51 so both sides of the `qp >= 24` branch are + /// covered (left-shift vs rounding-add-then-arithmetic-shift), and includes + /// negative levels and magnitudes near the coefficient range, because an + /// arithmetic vs logical shift confusion only shows on negatives. + #[test] + #[cfg(all(target_arch = "x86_64", feature = "asm"))] + fn dequant_4x4_matches_scalar() { + let mut st = 0x2f6e_1c37u32; + let mut rnd = || { + st ^= st << 13; + st ^= st >> 17; + st ^= st << 5; + st + }; + for qp in 0..=51u8 { + for case in 0..64 { + let levels: [i32; 16] = std::array::from_fn(|_| { + let r = rnd(); + let mag = match case % 4 { + 0 => (r & 0x7) as i32, + 1 => (r & 0x7ff) as i32, + 2 => (r & 0x7fff) as i32, + _ => 0, + }; + if r & 0x8000_0000 != 0 { -mag } else { mag } + }); + let m = (qp % 6) as usize; + let ls = &LEVEL_SCALE_FLAT[m]; + // scalar oracle, spelled out rather than calling `dequantize` (which + // now dispatches to the kernel under test). + let shift = (qp / 6) as i32; + let mut want = [0i32; 16]; + if qp >= 24 { + let sh = shift - 4; + for i in 0..16 { + want[i] = (levels[i] * ls[i]) << sh; + } + } else { + let add = 1 << (3 - shift); + let sh = 4 - shift; + for i in 0..16 { + want[i] = (levels[i] * ls[i] + add) >> sh; + } + } + let mut got = [0i32; 16]; + assert!(rusty_h264_accel::dequant_4x4(&mut got, &levels, ls, qp)); + assert_eq!(got, want, "qp={qp} case={case} levels={levels:?}"); + } + } + } + + #[test] + fn batched_forward_dct_matches_scalar() { + let mut state = 0x9e37_79b9u32; + let mut next = || { + state = state.wrapping_mul(1_664_525).wrapping_add(1_013_904_223); + ((state >> 16) % 511) as i32 - 255 + }; + for n in 1..=18 { + let res: Vec<[i32; 16]> = (0..n).map(|_| std::array::from_fn(|_| next())).collect(); + let mut out = vec![[0i32; 16]; n]; + forward_dct_blocks(&res, &mut out); + for (r, o) in res.iter().zip(&out) { + assert_eq!(&forward_core(r), o, "n={n}"); + } + } + } + + #[test] + fn batched_inverse_dct_matches_scalar() { + // Wider range than the forward test: dequantized coefficients can be large, + // and the `>> 1` inside the inverse butterfly must match the scalar's + // arithmetic shift on negative/asymmetric blocks exactly. + let mut state = 0x0bad_f00du32; + let mut next = || { + state = state.wrapping_mul(1_664_525).wrapping_add(1_013_904_223); + ((state >> 12) % 8191) as i32 - 4095 + }; + for n in 1..=18 { + let coeffs: Vec<[i32; 16]> = (0..n).map(|_| std::array::from_fn(|_| next())).collect(); + let mut out = vec![[0i32; 16]; n]; + inverse_dct_blocks(&coeffs, &mut out); + for (c, o) in coeffs.iter().zip(&out) { + assert_eq!(&inverse_core(c), o, "n={n}"); + } + } + } + + #[test] + fn simd_satd_matches_scalar() { + // The SIMD batch SATD must be bit-identical to the scalar per-block sum. + let scalar = |res: &[i32; 16]| -> i64 { + hadamard_4x4(res).iter().map(|&v| v.unsigned_abs() as i64).sum() + }; + // Deterministic pseudo-random residuals in [-255, 255], 1..=20 blocks. + let mut state = 0x1234_5678u32; + let mut next = || { + state = state.wrapping_mul(1_664_525).wrapping_add(1_013_904_223); + ((state >> 16) % 511) as i32 - 255 + }; + for n in 1..=20 { + let blocks: Vec<[i32; 16]> = + (0..n).map(|_| std::array::from_fn(|_| next())).collect(); + let expect: i64 = blocks.iter().map(&scalar).sum(); + assert_eq!(satd_4x4_sum(&blocks), expect, "n={n}"); + } + } + + #[test] + fn forward_inverse_core_are_consistent_scale() { + // A pure-DC block: every sample = 4. Forward DC should be 16*4=64, + // others ~0. Inverse of just the dequantized DC returns the flat block. + let block = [4i32; 16]; + let w = forward_core(&block); + assert_eq!(w[0], 64, "DC coefficient"); + for (k, &ac) in w.iter().enumerate().skip(1) { + assert_eq!(ac, 0, "AC[{k}] should be zero for a flat block"); + } + } + + #[test] + fn forward_core_8x8_flat_block_is_dc_only() { + // A flat 8×8 block transforms to DC only; the 8×8 DC gain is 64, so a + // block of all-4 has DC = 256 and zero AC. + let block = [4i32; 64]; + let w = forward_core_8x8(&block); + assert_eq!(w[0], 256, "8×8 DC coefficient"); + for (k, &ac) in w.iter().enumerate().skip(1) { + assert_eq!(ac, 0, "8×8 AC[{k}] should be zero for a flat block"); + } + } + + #[test] + fn inverse_core_8x8_dc_only_is_flat() { + // Inverse of a DC-only 8×8 block is a flat block of (DC + 32) >> 6. + let mut coeffs = [0i32; 64]; + coeffs[0] = 256; + let r = inverse_core_8x8(&coeffs); + for (k, &v) in r.iter().enumerate() { + assert_eq!(v, (256 + 32) >> 6, "8×8 inverse DC pixel {k}"); + } + } + + #[test] + fn quant_dequant_8x8_round_trip_near_identity() { + // The realistic invariant: forward → (flat) dequant-compensated → inverse + // recovers a flat block exactly, and a smooth ramp within a small error. + // (Core forward∘inverse alone is NOT identity — the inverse expects the + // per-frequency LevelScale that dequant applies; here we use the flat + // matched scale 16·normAdjust at a representative QP.) + let weight = [16i32; 64]; + for &val in &[0i32, 4, -7, 31] { + let block = [val; 64]; + let fwd = forward_core_8x8(&block); + // Treat the forward output as "levels" at QP where 16·normAdjust·>>6 + // is the identity DC gain; verify the DC pixel reconstructs to `val`. + let deq = dequantize_8x8(&fwd, 24, &weight); + let _ = deq; // dequant is exercised; exact recon validated via oracle. + let recon = inverse_core_8x8(&fwd); + assert_eq!(recon, block, "flat 8×8 must round-trip through the core"); + } + } + + #[test] + fn quantize_8x8_round_trips_through_the_decoder_path() { + // The encoder gate: forward_core_8x8 → quantize_8x8 → (decoder's) + // dequantize_8x8 → inverse_core_8x8 recovers the residual within the + // quantization error — and quant∘dequant is near-identity in coeff space. + let weight = [16i32; 64]; + // A realistic textured residual (deterministic). + let res: [i32; 64] = std::array::from_fn(|i| { + let (x, y) = (i % 8, i / 8); + (((x * 7 + y * 13) % 23) as i32 - 11) * 4 + ((x as i32 - y as i32) * 3) + }); + for &qp in &[12u8, 22, 30, 40, 48] { + let coeffs = forward_core_8x8(&res); + let levels = quantize_8x8(&coeffs, qp, &weight, 2); // round-to-nearest + // Coefficient round-trip: dequant(quant(c)) within one quant step of c. + let deq = dequantize_8x8(&levels, qp, &weight); + for i in 0..64 { + // step ≈ 2^(qp/6) scaled; a generous bound catches gross scale errors. + let step = (1i32 << (qp / 6)) * 64; + assert!( + (deq[i] - coeffs[i]).abs() <= step, + "qp{qp} pos{i}: dequant {} vs coeff {} exceeds step {step}", + deq[i], + coeffs[i] + ); + } + // Full residual recon: mean-abs error grows with QP but stays bounded. + let recon = inverse_core_8x8(&deq); + let mae: i32 = + (0..64).map(|i| (recon[i] - res[i]).abs()).sum::() / 64; + let bound = 2 + (1i32 << (qp / 6)); // ~half a quant step + assert!(mae <= bound, "qp{qp}: 8×8 recon MAE {mae} exceeds {bound}"); + } + } + + #[test] + fn dequant_8x8_flat_matches_levelscale() { + // Flat weight (16) → LevelScale = 16·normAdjust8x8; check one DC sample. + let mut levels = [0i32; 64]; + levels[0] = 3; + let weight = [16i32; 64]; + let d = dequantize_8x8(&levels, 30, &weight); + // qp=30 < 36: (3 · 16·normAdjust[0][0] + (1<<(5-5))) >> (6-5) + let ls = 16 * NORM_ADJUST_8X8[0][0]; + assert_eq!(d[0], (3 * ls + 1) >> 1); + } + + #[test] + fn inverse_core_is_row_first() { + // The 4×4 integer inverse transform is NOT order-invariant: the `>> 1` + // flooring inside `inv_1d` makes row-first and column-first diverge on + // asymmetric blocks. The spec (§8.5.12.2) and ffmpeg do rows first; a + // column-first pass is a real bug that only surfaces at low QP / high + // frequency. This input distinguishes the two orders and pins ours. + let coeffs = [9, 2, -1, 2, -2, 2, -2, 1, -1, -2, 3, 5, -1, -1, -5, 3]; + let mut rows_then_cols = coeffs; + for r in 0..4 { + let (a, b, c, d) = inv_1d( + rows_then_cols[r * 4], + rows_then_cols[r * 4 + 1], + rows_then_cols[r * 4 + 2], + rows_then_cols[r * 4 + 3], + ); + rows_then_cols[r * 4] = a; + rows_then_cols[r * 4 + 1] = b; + rows_then_cols[r * 4 + 2] = c; + rows_then_cols[r * 4 + 3] = d; + } + for c in 0..4 { + let (a, b, cc, d) = inv_1d( + rows_then_cols[c], + rows_then_cols[4 + c], + rows_then_cols[8 + c], + rows_then_cols[12 + c], + ); + rows_then_cols[c] = a; + rows_then_cols[4 + c] = b; + rows_then_cols[8 + c] = cc; + rows_then_cols[12 + c] = d; + } + let mut cols_then_rows = coeffs; + for c in 0..4 { + let (a, b, cc, d) = inv_1d( + cols_then_rows[c], + cols_then_rows[4 + c], + cols_then_rows[8 + c], + cols_then_rows[12 + c], + ); + cols_then_rows[c] = a; + cols_then_rows[4 + c] = b; + cols_then_rows[8 + c] = cc; + cols_then_rows[12 + c] = d; + } + for r in 0..4 { + let (a, b, c, d) = inv_1d( + cols_then_rows[r * 4], + cols_then_rows[r * 4 + 1], + cols_then_rows[r * 4 + 2], + cols_then_rows[r * 4 + 3], + ); + cols_then_rows[r * 4] = a; + cols_then_rows[r * 4 + 1] = b; + cols_then_rows[r * 4 + 2] = c; + cols_then_rows[r * 4 + 3] = d; + } + // The two orders genuinely differ on this block... + assert_ne!(rows_then_cols, cols_then_rows); + // ...and inverse_core (plus the +32>>6 normalization) follows rows-first. + let expected: [i32; 16] = + core::array::from_fn(|k| (rows_then_cols[k] + 32) >> 6); + assert_eq!(inverse_core(&coeffs), expected); + } + + #[test] + fn quant_dequant_roundtrip_is_near_identity() { + // For a range of QPs, a transformed-then-quantized-then-reconstructed + // residual should stay within the quantization step of the original. + let residual: [i32; 16] = [ + 5, -3, 8, 0, 12, -7, 2, 1, -4, 6, 9, -2, 0, 3, -1, 7, + ]; + for qp in [0u8, 6, 12, 18, 26, 30, 37, 45, 51] { + let levels = forward_quant(&residual, qp, true); + let recon = inverse_quant(&levels, qp); + // Tolerance grows with the quant step (~ 2^(qp/6)). + let tol = 2 + (1 << (qp / 6)); + for k in 0..16 { + let diff = (recon[k] - residual[k]).abs(); + assert!( + diff <= tol, + "qp {qp}: residual[{k}]={} recon={} diff={diff} tol={tol}", + residual[k], + recon[k] + ); + } + } + } + + #[test] + fn trellis_never_exceeds_scalar_magnitude() { + // Trellis only considers the scalar level or lower, so |level| never + // grows, and a large λ drives marginal coefficients toward zero. + let coeffs: [i32; 16] = [120, -40, 8, 1, -15, 6, -1, 0, 3, -2, 1, 0, 0, 1, 0, 0]; + let scalar = quantize(&coeffs, 26, 3); + let t = trellis_quant(&coeffs, 26, true, 50.0); + for k in 0..16 { + assert!(t[k].unsigned_abs() <= scalar[k].unsigned_abs(), "[{k}]"); + assert!(t[k] == 0 || t[k].signum() == scalar[k].signum()); + } + } + + #[test] + fn zero_residual_stays_zero() { + let zero = [0i32; 16]; + let levels = forward_quant(&zero, 28, true); + assert_eq!(levels, [0i32; 16]); + assert_eq!(inverse_quant(&levels, 28), [0i32; 16]); + } + + #[test] + fn luma_dc_end_to_end_flat_block() { + // A flat luma residual `r`: each 4×4 block's forward-core DC is 16*r and + // its AC is 0. Coding the 16 DCs via the secondary transform and + // reconstructing (scatter DC → inverse core) must recover ~r per sample. + for r in [3i32, 9, -5, 20] { + for qp in [0u8, 12, 24, 30] { + let w_dc = [16 * r; 16]; // forward-core DC of a flat block + let z = forward_quant_luma_dc(&w_dc, qp, true); + let dcy = inverse_quant_luma_dc(&z, qp); + let tol = 1 + (1 << (qp / 6)); + for (b, &dc) in dcy.iter().enumerate() { + let mut coeff = [0i32; 16]; + coeff[0] = dc; + let res = inverse_core(&coeff); + for &v in &res { + assert!((v - r).abs() <= tol, "luma DC r={r} qp{qp} blk{b}: {v} vs {r}"); + } + } + } + } + } + + #[test] + fn chroma_dc_end_to_end_flat_block() { + // Same idea for the 2×2 chroma DC secondary transform. + for r in [4i32, -6, 11] { + for qp in [0u8, 18, 30] { + let dc = [16 * r; 4]; + let z = forward_quant_chroma_dc(&dc, qp, true); + let dcy = inverse_quant_chroma_dc(&z, qp); + let tol = 1 + (1 << (qp / 6)); + for &d in &dcy { + let mut coeff = [0i32; 16]; + coeff[0] = d; + let res = inverse_core(&coeff); + for &v in &res { + assert!((v - r).abs() <= tol, "chroma DC r={r} qp{qp}: {v} vs {r}"); + } + } + } + } + } + + #[test] + fn hadamard_is_self_inverse_scaled() { + // Applying the 4×4 Hadamard twice scales by 16. + let x: [i32; 16] = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16]; + let twice = hadamard_4x4(&hadamard_4x4(&x)); + for (k, (&a, &b)) in x.iter().zip(twice.iter()).enumerate() { + assert_eq!(b, a * 16, "[{k}]"); + } + } + + #[test] + fn low_qp_is_high_fidelity() { + // At QP 0 the reconstruction should be essentially exact for small + // integer residuals. + let residual: [i32; 16] = [1, 2, 3, 4, -1, -2, -3, -4, 0, 1, 0, -1, 2, -2, 1, 0]; + let levels = forward_quant(&residual, 0, true); + let recon = inverse_quant(&levels, 0); + for (k, (&r, &o)) in residual.iter().zip(recon.iter()).enumerate() { + assert!((o - r).abs() <= 1, "qp0 residual[{k}]={r} recon={o}"); + } + } +} + +// openh264 BSD-2 quant tables (g_kiQuantMF[52][8], g_kiQuantInterFF[58][8]). +pub const QUANT_MF_OH: [[i16; 8]; 52] = [ + [26214, 16132, 26214, 16132, 16132, 10486, 16132, 10486], + [23832, 14980, 23832, 14980, 14980, 9320, 14980, 9320], + [20164, 13108, 20164, 13108, 13108, 8388, 13108, 8388], + [18724, 11650, 18724, 11650, 11650, 7294, 11650, 7294], + [16384, 10486, 16384, 10486, 10486, 6710, 10486, 6710], + [14564, 9118, 14564, 9118, 9118, 5786, 9118, 5786], + [13107, 8066, 13107, 8066, 8066, 5243, 8066, 5243], + [11916, 7490, 11916, 7490, 7490, 4660, 7490, 4660], + [10082, 6554, 10082, 6554, 6554, 4194, 6554, 4194], + [9362, 5825, 9362, 5825, 5825, 3647, 5825, 3647], + [8192, 5243, 8192, 5243, 5243, 3355, 5243, 3355], + [7282, 4559, 7282, 4559, 4559, 2893, 4559, 2893], + [6554, 4033, 6554, 4033, 4033, 2622, 4033, 2622], + [5958, 3745, 5958, 3745, 3745, 2330, 3745, 2330], + [5041, 3277, 5041, 3277, 3277, 2097, 3277, 2097], + [4681, 2913, 4681, 2913, 2913, 1824, 2913, 1824], + [4096, 2622, 4096, 2622, 2622, 1678, 2622, 1678], + [3641, 2280, 3641, 2280, 2280, 1447, 2280, 1447], + [3277, 2017, 3277, 2017, 2017, 1311, 2017, 1311], + [2979, 1873, 2979, 1873, 1873, 1165, 1873, 1165], + [2521, 1639, 2521, 1639, 1639, 1049, 1639, 1049], + [2341, 1456, 2341, 1456, 1456, 912, 1456, 912], + [2048, 1311, 2048, 1311, 1311, 839, 1311, 839], + [1821, 1140, 1821, 1140, 1140, 723, 1140, 723], + [1638, 1008, 1638, 1008, 1008, 655, 1008, 655], + [1490, 936, 1490, 936, 936, 583, 936, 583], + [1260, 819, 1260, 819, 819, 524, 819, 524], + [1170, 728, 1170, 728, 728, 456, 728, 456], + [1024, 655, 1024, 655, 655, 419, 655, 419], + [910, 570, 910, 570, 570, 362, 570, 362], + [819, 504, 819, 504, 504, 328, 504, 328], + [745, 468, 745, 468, 468, 291, 468, 291], + [630, 410, 630, 410, 410, 262, 410, 262], + [585, 364, 585, 364, 364, 228, 364, 228], + [512, 328, 512, 328, 328, 210, 328, 210], + [455, 285, 455, 285, 285, 181, 285, 181], + [410, 252, 410, 252, 252, 164, 252, 164], + [372, 234, 372, 234, 234, 146, 234, 146], + [315, 205, 315, 205, 205, 131, 205, 131], + [293, 182, 293, 182, 182, 114, 182, 114], + [256, 164, 256, 164, 164, 105, 164, 105], + [228, 142, 228, 142, 142, 90, 142, 90], + [205, 126, 205, 126, 126, 82, 126, 82], + [186, 117, 186, 117, 117, 73, 117, 73], + [158, 102, 158, 102, 102, 66, 102, 66], + [146, 91, 146, 91, 91, 57, 91, 57], + [128, 82, 128, 82, 82, 52, 82, 52], + [114, 71, 114, 71, 71, 45, 71, 45], + [102, 63, 102, 63, 63, 41, 63, 41], + [93, 59, 93, 59, 59, 36, 59, 36], + [79, 51, 79, 51, 51, 33, 51, 33], + [73, 46, 73, 46, 46, 28, 46, 28], +]; + +pub const QUANT_FF_OH: [[i16; 8]; 58] = [ + [0, 1, 0, 1, 1, 1, 1, 1], + [0, 1, 0, 1, 1, 1, 1, 1], + [1, 1, 1, 1, 1, 1, 1, 1], + [1, 1, 1, 1, 1, 1, 1, 1], + [1, 1, 1, 1, 1, 2, 1, 2], + [1, 1, 1, 1, 1, 2, 1, 2], + [1, 1, 1, 1, 1, 2, 1, 2], + [1, 1, 1, 1, 1, 2, 1, 2], + [1, 2, 1, 2, 2, 3, 2, 3], + [1, 2, 1, 2, 2, 3, 2, 3], + [1, 2, 1, 2, 2, 3, 2, 3], + [1, 2, 1, 2, 2, 4, 2, 4], + [2, 3, 2, 3, 3, 4, 3, 4], + [2, 3, 2, 3, 3, 5, 3, 5], + [2, 3, 2, 3, 3, 5, 3, 5], + [2, 4, 2, 4, 4, 6, 4, 6], + [3, 4, 3, 4, 4, 7, 4, 7], + [3, 5, 3, 5, 5, 8, 5, 8], + [3, 5, 3, 5, 5, 8, 5, 8], + [4, 6, 4, 6, 6, 9, 6, 9], + [4, 7, 4, 7, 7, 10, 7, 10], + [5, 8, 5, 8, 8, 12, 8, 12], + [5, 8, 5, 8, 8, 13, 8, 13], + [6, 10, 6, 10, 10, 15, 10, 15], + [7, 11, 7, 11, 11, 17, 11, 17], + [7, 12, 7, 12, 12, 19, 12, 19], + [9, 13, 9, 13, 13, 21, 13, 21], + [9, 15, 9, 15, 15, 24, 15, 24], + [11, 17, 11, 17, 17, 26, 17, 26], + [12, 19, 12, 19, 19, 30, 19, 30], + [13, 22, 13, 22, 22, 33, 22, 33], + [15, 23, 15, 23, 23, 38, 23, 38], + [17, 27, 17, 27, 27, 42, 27, 42], + [19, 30, 19, 30, 30, 48, 30, 48], + [21, 33, 21, 33, 33, 52, 33, 52], + [24, 38, 24, 38, 38, 60, 38, 60], + [27, 43, 27, 43, 43, 67, 43, 67], + [29, 47, 29, 47, 47, 75, 47, 75], + [35, 53, 35, 53, 53, 83, 53, 83], + [37, 60, 37, 60, 60, 96, 60, 96], + [43, 67, 43, 67, 67, 104, 67, 104], + [48, 77, 48, 77, 77, 121, 77, 121], + [53, 87, 53, 87, 87, 133, 87, 133], + [59, 93, 59, 93, 93, 150, 93, 150], + [69, 107, 69, 107, 107, 167, 107, 167], + [75, 120, 75, 120, 120, 192, 120, 192], + [85, 133, 85, 133, 133, 208, 133, 208], + [96, 153, 96, 153, 153, 242, 153, 242], + [107, 173, 107, 173, 173, 267, 173, 267], + [117, 187, 117, 187, 187, 300, 187, 300], + [139, 213, 139, 213, 213, 333, 213, 333], + [149, 240, 149, 240, 240, 383, 240, 383], + [171, 267, 171, 267, 267, 417, 267, 417], + [192, 307, 192, 307, 307, 483, 307, 483], + [213, 347, 213, 347, 347, 533, 347, 533], + [235, 373, 235, 373, 373, 600, 373, 600], + [277, 427, 277, 427, 427, 667, 427, 667], + [299, 480, 299, 480, 480, 767, 480, 767], +]; diff --git a/vendor/rusty_h264-common/src/types.rs b/vendor/rusty_h264-common/src/types.rs new file mode 100644 index 0000000..a155314 --- /dev/null +++ b/vendor/rusty_h264-common/src/types.rs @@ -0,0 +1,97 @@ +//! Shared codec types: profiles, chroma format, and the raw YUV frame container. + +/// H.264 profile. The encoder targets Constrained Baseline; the rest are named +/// for parsing/identification only. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub enum Profile { + /// Constrained Baseline (`profile_idc = 66` with `constraint_set1_flag`). + ConstrainedBaseline, + /// Baseline (`profile_idc = 66`). + Baseline, + /// Main (`profile_idc = 77`). + Main, + /// High (`profile_idc = 100`). + High, + /// Any other `profile_idc`. + Other(u8), +} + +impl Profile { + /// The `profile_idc` byte written into the SPS. + pub fn profile_idc(self) -> u8 { + match self { + Profile::ConstrainedBaseline | Profile::Baseline => 66, + Profile::Main => 77, + Profile::High => 100, + Profile::Other(v) => v, + } + } +} + +/// Chroma subsampling. The encoder supports 4:2:0 only for now. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub enum ChromaFormat { + /// Monochrome (`chroma_format_idc = 0`). + Monochrome, + /// 4:2:0 (`chroma_format_idc = 1`). + Yuv420, +} + +impl ChromaFormat { + /// `chroma_format_idc`. + pub fn idc(self) -> u8 { + match self { + ChromaFormat::Monochrome => 0, + ChromaFormat::Yuv420 => 1, + } + } +} + +/// A raw planar YUV 4:2:0 frame (8-bit). Plane strides equal their widths; +/// chroma planes are half-resolution in each dimension. +#[derive(Debug, Clone, PartialEq, Eq)] +pub struct YuvFrame { + /// Luma width in pixels. + pub width: usize, + /// Luma height in pixels. + pub height: usize, + /// Y plane, `width * height` bytes. + pub y: Vec, + /// Cb plane, `(width/2) * (height/2)` bytes. + pub u: Vec, + /// Cr plane, `(width/2) * (height/2)` bytes. + pub v: Vec, +} + +impl YuvFrame { + /// Allocates a black (Y=0, U=V=128) frame. Dimensions must be even. + pub fn black(width: usize, height: usize) -> Self { + assert!(width % 2 == 0 && height % 2 == 0, "dimensions must be even"); + let cw = width / 2; + let ch = height / 2; + Self { + width, + height, + y: vec![0; width * height], + u: vec![128; cw * ch], + v: vec![128; cw * ch], + } + } + + /// Chroma plane width. + pub fn chroma_width(&self) -> usize { + self.width / 2 + } + + /// Chroma plane height. + pub fn chroma_height(&self) -> usize { + self.height / 2 + } + + /// Validates plane sizes against the dimensions. + pub fn is_valid(&self) -> bool { + self.y.len() == self.width * self.height + && self.u.len() == self.chroma_width() * self.chroma_height() + && self.v.len() == self.chroma_width() * self.chroma_height() + } +}