Skip to content

av1enc: truncate instead of floor, log2 lookup table, skip division in the dead zone - #2400

Merged
bflatastic merged 2 commits into
storytold:mainfrom
vangel76:av1enc-quant-tables
Oct 29, 2026
Merged

bflatastic merged 2 commits into
storytold:mainfrom
vangel76:av1enc-quant-tables

Conversation

@vangel76

@vangel76 vangel76 commented Oct 25, 2026 •

Copy link
Copy Markdown
Contributor

Fixes #2373

What

In crates/av1enc/src/decide.rs:

  • The quantiser used (x / q + rnd).floor() as i32, a libm floorf call per coefficient on baseline x86-64. The operand is never negative, so as i32 (truncation) gives the same value, with the same saturation.
  • estimate_bits (eob and level magnitudes) and the motion-vector cost in motion_search called f64::log2. They now read a 1025-entry table built with the same f64::log2 call, so the values are bit-identical. Larger arguments fall back to the direct call.
  • Coefficients that quantise to zero no longer go through the f32 division. The smallest magnitude that quantises to a non-zero level is found once per Decider (DC and AC, inter and intra rounding offset) by a binary search over the f32 bit patterns of the monotone expression, so the shortcut is exact.

Output

Bit-identical. md5 of the encoded stream equal to upstream/main (9919048) at 5 operating points (1080p synthetic pan + noise):

operating point md5 (both)
Q76, 8 frames, keyint 30 06cc3ba1eb1de9d9531ed5added5d205
bitrate 10000 kbit/s, 60 frames, keyint 60 e82e44150c0a6ad652bbbcbba9089bf8
noise 3, q50, 6 frames 8e6b245affb1ba56ee643b3fc1a71713
noise 3, q90, 6 frames efeeaabcb9a9f9a90b4d6ffb59ee0031
noise 3, q130 / q170, 6 frames 3001ce9ac42f0263bafbee80aff1c55d / cdca365328fcb366eb77f0f22571a25f

cargo test --release -p effectcraft-av1enc passes (roundtrip decoder == reconstruction, ffmpeg/libdav1d oracle, sizes 1x1..4K, 8 and 10 bit). Two new unit tests: the new quantiser equals the old expression at the threshold boundary (+-3 ulp) and on random values for every quantiser index of all three bit-depth tables and both rounding offsets; the table equals f64::log2 bit for bit.

Speed

perf stat -e instructions:u,cycles:u, one thread pinned to one core, base and branch alternating, 5 rounds, medians, 1080p synthetic sequence, 8 frames:

config instructions cycles wall
Q76, keyint 30 base 107.25 G 24.97 G 5.21 s
branch 103.32 G (-3.7 %) 23.37 G (-6.4 %) 4.89 s (-6.2 %)
bitrate 10000 kbit/s, keyint 60 base 212.33 G 53.15 G 11.16 s
branch 204.93 G (-3.5 %) 49.66 G (-6.6 %) 10.31 s (-7.6 %)

🤖 Generated with Claude Code

Summary by CodeRabbit

  • Performance
    • Improved AV1 encoding efficiency through faster coefficient quantization and bit estimation.
  • Reliability
    • Added checks to verify quantization behavior at threshold values and confirm bit-estimation accuracy.

…n the dead zone

The quantiser in try_tx called libm floorf for every coefficient, estimate_bits
and the motion-vector cost called f64::log2, and coefficients that quantise to
zero still went through an f32 division.

- (x / q + rnd).floor() as i32 becomes (x / q + rnd) as i32: the operand is
  never negative, so truncation equals floor.
- log2 of small integers comes from a table built with the same f64::log2
  call (estimate_bits and the MV cost in motion_search), so the values are
  bit-identical.
- Coefficients below an exact per-(q, rounding offset) threshold are zero
  without dividing. The threshold is found once per Decider by a binary
  search over f32 bit patterns of the monotone quantiser expression.

The encoded stream is unchanged. Unit tests compare the new quantiser with the
old expression at the threshold boundary and on random values for every
quantiser index, and the table with f64::log2.

Fixes storytold#2373

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
@coderabbitai

coderabbitai Bot commented Oct 25, 2026 •

Copy link
Copy Markdown

Review in Change Stack →

No actionable comments were generated in the recent review.

Recent review info
Run configuration
Commits

Reviewing files that changed from the base of the PR and between 12af1c1 and 88c02a9.

Files selected for processing: 1
  • crates/av1enc/src/decide.rs

Included review availability: This review used your included allowance. Your plan provides up to 10 included reviews per hour; 9 remain after this review.

Walkthrough

The AV1 encoder now precomputes zero-quantization thresholds and skips division for coefficients below them. Motion-vector and coefficient bit estimates use a shared cached log2 table for values below 1025 and direct log2 for larger values.

Changes: AV1 encoder decision-cost optimizations

Layer / File(s) Summary
Zero-threshold quantization
crates/av1enc/src/decide.rs
Decider stores inter/intra DC/AC thresholds. try_tx skips coefficients below the selected threshold and truncates the rounded quotient. Tests compare the threshold quantizer with the previous formula.
Logarithm-based bit estimates
crates/av1enc/src/decide.rs
Motion-vector and coefficient bit estimates use the shared logarithm lookup. Tests compare lookup results with direct log2 values.

Priority: Low

Estimated code review effort: 2 (Simple) | ~12 minutes

Change: Refactor

Suggested reviewers: echelon

Merge Risk: Minimal · up to 88c02

No merge-blocking risk was identified in the quantization or bit-estimation changes.

Pre-merge checks: Passed 4 · Failed 1

Failed Failed checks: 1 warning

Check name Status Explanation Resolution
Docstring Coverage Warning Docstring coverage is 44.44% which is insufficient. The required threshold is 80.00%. Docstring coverage is scoped to functions touched by this diff with cyclomatic complexity of at least 2. Documenta… Write docstrings for the functions missing them to satisfy the coverage threshold.
Passed Passed checks: 4 passed
Check name Status Explanation
Description Check Passed Check skipped - CodeRabbit’s high-level summary is enabled.
Title check Passed The title accurately summarizes the main changes: integer truncation, a log2 lookup table, and division skipping in the quantization dead zone.
Linked Issues check Passed Issue #2373 requires truncation where it matches floor(), exact log2 lookup values with fallback, and an exact dead-zone threshold. The reviewed changes implement these items in `crates/av1enc/src…
Out of Scope Changes check Passed The reviewed change is limited to crates/av1enc/src/decide.rs. The implementation and tests directly support issue #2373 performance and output-preservation requirements. No unrelated change is evid…
Full details: Linked Issues check

Explanation

Issue #2373 requires truncation where it matches floor(), exact log2 lookup values with fallback, and an exact dead-zone threshold. The reviewed changes implement these items in crates/av1enc/src/decide.rs. The changes add DC/AC inter/intra thresholds, skip division below the applicable threshold, use truncating conversion, and use a shared 1025-entry table with direct f64::log2 fallback. Unit tests cover quantiser equivalence at threshold boundaries and sampled values, plus bit-exact table values. The PR reports bit-identical output validation and passing encoder tests.

Full details: Out of Scope Changes check

Explanation

The reviewed change is limited to crates/av1enc/src/decide.rs. The implementation and tests directly support issue #2373 performance and output-preservation requirements. No unrelated change is evident.

Full details: Docstring Coverage

Explanation

Docstring coverage is 44.44% which is insufficient. The required threshold is 80.00%. Docstring coverage is scoped to functions touched by this diff with cyclomatic complexity of at least 2. Documentation-only edits and deletions within surviving functions are included; unchanged diff context and fully deleted functions are excluded. Analyzed 9 functions across 1 files.

Resolution

Write docstrings for the functions missing them to satisfy the coverage threshold.

Finishing Touches
🧪 Generate unit tests (beta)
  • Create a new PR
  • Autofix · Keep fixing CodeRabbit findings and required CI, and resolving merge conflicts

Comment @coderabbitai help to get the list of available commands.

@vangel76

Copy link
Copy Markdown
Contributor Author

This PR is one of five output-identical speed PRs for the AV1 encoder (effectcraft-av1enc): #2396 (transform specialisation), #2401 (half-pel planes in one pass), #2400 (quantiser tables), #2405 (scratch buffers), #2406 (motion search, SATD, decoded-flag snapshot). Each PR has its own table; this is the measurement of all five merged together (upstream/main + the five branches; the decide.rs conflicts are trivial) against upstream/main.

1080p, one thread base all five merged
Q76, 8 frames: instructions 107.3 G 64.6 G -39.7 %
Q76: cycles (median) 42.8 G 27.5 G -35.8 %
Q76: frames/s (best of 5 rounds) 1.55 2.20 +42 %
bitrate 10000 kbit/s, keyint 60, 60 frames: instructions 1133 G 670 G -40.9 %
bitrate: cycles (median) 351 G 237 G -32.4 %
bitrate: frames/s (best of 5 rounds) 0.91 1.39 +53 %

@bflatastic

Copy link
Copy Markdown
Member

Thanks @vangel76! This conflicts with #2405 in av1enc/src/decide.rs (~L873): levels is now a reused scratch buffer (levels.fill(0)) rather than a fresh vec!. Please rebase and keep the scratch buffer; your continue works with fill(0). Also recheck against #2401, which is landing in the same file.

# Conflicts:
#	crates/av1enc/src/decide.rs
@vangel76

Copy link
Copy Markdown
Contributor Author

Merged current main into the branch. The only conflict was in decide.rs, next to the TransformBlock refactor; the quantiser changes are intact and the av1enc tests pass, including the dead-zone and log2 table equality tests.

@bflatastic
bflatastic merged commit 1cb8c40 into storytold:main Oct 29, 2026
6 checks passed
@bflatastic

Copy link
Copy Markdown
Member

Merged, thank you @vangel76! It landed on main with a batch of community PRs, after a full workspace build and test run on Windows against the refactored main (fmt, strict clippy, about 4,100 tests, layers, assets and wasm).

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

av1enc: quantiser uses libm floor/log2 and divides dead-zone coefficients (-6 %)

2 participants