Skip to content

refactor(dither): extract binary dithering into a tested, zero-cost, disableable module (#4672) - #4673

Merged
zackees merged 3 commits into
masterfrom
refactor/binary-dither-module-4672
Oct 2, 2026
Merged

zackees merged 3 commits into
masterfrom
refactor/binary-dither-module-4672

Conversation

@zackees

@zackees zackees commented Oct 2, 2026 •

Copy link
Copy Markdown
Member

Closes #4672.

What

Temporal binary dithering moves out of PixelController into a header-only module, src/fl/gfx/binary_dither.h, with two policies that share one static interface:

  • fl::BinaryDither: phase, offset, init, reseed, clear, active, step, stepChannel, apply.
  • fl::NoDither: init zeroes d/e; everything else is a no-op or the identity.
  • fl::Dither: the one in use, selected by NO_DITHERING. One switch disables it, and the work is compiled out rather than run against zeros.

PixelController keeps its public d[3]/e[3] and its method names, so the AVR/ATtiny clockless asm and the M0, LPC, nRF51 and Teensy drivers are untouched. Each method is now a one-line forward. init and reseed share one phase() instead of two copies of the bit reversal. The three open-coded (e[0]|e[1]|e[2]) != 0 checks in fl/channels become pixels.ditherActive().

Bug fixed

Under NO_DITHERING (every FL_IS_AVR_LIMITED part), init_binary_dithering() compiled to an empty body while the default mode is still BINARY_DITHER, so d/e were never written. The AVR asm adds them to every byte it sends. This happens whenever dithering is turned back on after the first show() (FastLED.setDither(BINARY_DITHER)), or when a controller is driven directly. NoDither::init now clears them, and it costs nothing (see the sizes below).

Why u8 (&)[3] and not fl::span<T, 3>

I measured each option on uno/Blink (master 5170 B):

API image_flash enable_dithering
u8* 5186 (+16) 146
fl::span<T,3> 5192 (+22) 146
fl::span<T,3> + force-inline accessors 5186 (+16) 146
u8 (&)[3] 5158 (−12) 118

With pointers or spans, GCC keeps three induction pointers in the init loop, which costs two extra register saves and pointer bookkeeping. Array references fold back to fixed offsets from this, the same codegen as the old member code.

AVR size (bash bloat <board> --example <ex> --build, image_flash in bytes)

board sketch master this PR Δ
attiny85 Apa102 3000 2882 -118
attiny85 Blink 3492 3464 -28
attiny85 ColorPalette 4850 4822 -28
leonardo Apa102 6534 6522 -12
leonardo Blink 7098 7086 -12
leonardo ColorPalette 8640 8628 -12
nano_every Apa102 5463 5451 -12
nano_every Blink 6272 6260 -12
nano_every ColorPalette 7807 7795 -12
uno Apa102 4522 4510 -12
uno Blink 5170 5158 -12
uno ColorPalette 6624 6612 -12

RAM is unchanged in all 12 builds.

Tests

tests/fl/gfx/binary_dither.cpp (10 cases):

  • the phase table;
  • byte-for-byte equality with a verbatim copy of the pre-extraction algorithm, over every scale × frame;
  • reseed == init;
  • step is an involution, and stepChannel touches only its own channel;
  • the black floor and saturation;
  • active;
  • the cycle-average accuracy bound: total error below 0.55× the undithered error, and no code off by a whole step;
  • NoDither;
  • PixelController binding.

Also run:

  • bash test --cpp: 316/316 unit, 95/95 examples.
  • bash test binary_dither --debug (ASAN/UBSAN): clean.
  • bash lint: clean.

Production path

Every CPixelLEDController::show() builds a PixelController, which now calls fl::Dither. The Channel / SlimSpiBridgeController / ColorManagedPixelSource paths go through ditherActive() and reseed_binary_dithering().

Summary by CodeRabbit

  • New Features
    • Added temporal binary dithering to smooth brightness levels across frames while preserving black pixels. Dithering behavior can be configured to suit different output needs.
  • Bug Fixes
    • Dithering now reseeds only when active, avoiding unnecessary reseeds caused by leftover pixel-error values.
    • Dithering status now reflects whether dithering is enabled, keeping behavior consistent across pixel output paths.

#4672)

Temporal binary dithering moves out of PixelController into a header-only
module with two policies sharing one static interface:

- fl::BinaryDither: phase/offset/init/reseed/clear/active/step/stepChannel/apply
- fl::NoDither: init zeroes d/e, everything else is a no-op or identity
- fl::Dither: selected by NO_DITHERING

PixelController keeps its public d[3]/e[3] (the AVR, M0 and Teensy drivers
read them by name) and its method names; each now forwards to fl::Dither.
init and reseed share one phase() instead of two copies of the bit reversal,
and the three open-coded (e[0]|e[1]|e[2]) checks become ditherActive().

Fixes uninitialised d/e under NO_DITHERING (all FL_IS_AVR_LIMITED parts):
init_binary_dithering() was compiled empty while the default mode is still
BINARY_DITHER, so the AVR clockless asm added stack garbage to every byte
whenever dithering was re-enabled after the first show() or a controller was
driven directly. NoDither::init now clears them.

The API takes u8 (&)[3] rather than u8* or fl::span<T,3>: with pointers or
spans GCC keeps three induction pointers in the init loop (+16..+22 B on uno);
array references fold back to member offsets of `this`.

AVR image_flash vs master (Blink/Apa102/ColorPalette): uno, leonardo,
nano_every -12 B each; attiny85 -28/-118/-28 B. RAM unchanged.

Tests: tests/fl/gfx/binary_dither.cpp covers the phase table, byte-for-byte
equality with the pre-extraction algorithm over every scale x frame,
reseed == init, step involution, black floor and saturation, cycle-average
accuracy, NoDither, and PixelController binding.
@zackees zackees added the ci-full Run the complete release-equivalent CI matrix on this PR SHA label Oct 2, 2026
@coderabbitai

coderabbitai Bot commented Oct 2, 2026 •

Copy link
Copy Markdown

Review in Change Stack →

Navigate logical layers of code changes, visualize relationships, and explore their blast radius.

🧰 Additional context used
📚 Code guidelines (1)
.cursorrules — auto-discovered

No actionable comments were generated in the recent review. 🎉

ℹ️ Recent review info
⚙️ Run configuration
  • Configuration used: Repository: FastLED/FastLED/.coderabbit.yaml
  • Review profile: CHILL
  • Plan: Advanced
  • Run ID: a278afe7-8558-4df8-b406-1ffd2a5bf9dd
📥 Commits

Reviewing files that changed from the base of the PR and between 492d1b4 and 989aeea.

📒 Files selected for processing (2)
  • src/fl/gfx/binary_dither.h
  • src/pixel_controller.h

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


📝 Walkthrough

Walkthrough

The pull request extracts binary dithering into a shared header with enabled and disabled policies. PixelController delegates dithering operations to the selected policy, and three callers use its activity check.

Changes

Binary dithering

Layer / File(s) Summary
Dithering policies and algorithm
src/fl/gfx/binary_dither.h, tests/fl/gfx/binary_dither.cpp
The new header provides BinaryDither, NoDither, and the fl::Dither policy selection. Tests cover phases, initialization, reseeding, stepping, byte application, cycle averages, and disabled behavior.
PixelController delegation
src/pixel_controller.h, tests/fl/gfx/binary_dither.cpp
PixelController delegates dithering initialization, reseeding, activity checks, clearing, stepping, and byte application to fl::Dither. Integration tests compare controller state with the selected policy.
Dither activity checks
src/fl/channels/channel.cpp.hpp, src/fl/channels/color_managed_source.cpp.hpp, src/fl/channels/slim_spi_bridge_controller.h
The three callers use ditherActive() instead of checking whether any of the controller's error accumulators is nonzero.

Priority: ⬇️ Low

Estimated code review effort: 3 (Moderate) | ~20 minutes

Change: Refactor · Severity of issue fixed: Low

Merge Risk: ⚪ Minimal · up to 989ae

Enabled dithering behavior is preserved, while disabled dithering now starts from cleared state. No material merge-blocking behavior change was identified.

Architecture Summary

Architecture risk: 🔵 Low · up to 989ae

The change affects 2 systems.

Changed systems: src, tests

Architecture concerns
No architecture-level concerns identified.

Review details

Systems and components

  • observed — src (service) was modified; 5 changed files map to changed impact.
  • observed — tests (service) was modified; 1 changed file maps to changed impact.

Before / after behavior

  • observed — Modified behavior in src/fl/channels/channel.cpp.hpp: encodeFrame now uses ditherActive() to decide whether to reseed binary dithering, replacing the direct bitwise test of the three error accumulators.
  • observed — Modified behavior in src/fl/channels/color_managed_source.cpp.hpp: temporalDitherEnabled now uses the controller’s ditherActive() result instead of testing whether any of e[0], e[1], or e[2] is nonzero.
  • observed — Modified behavior in src/fl/channels/slim_spi_bridge_controller.h: Dithering is now reseeded only when pixels.ditherActive() is true; previously, it was reseeded when any of pixels.e[0], pixels.e[1], or pixels.e[2] was nonzero.
  • observed — Modified behavior in tests/fl/gfx/binary_dither.cpp: Adds a test-local reference implementation of the previous initialization calculation and a helper for initializing all three channels with one scale.
🚥 Pre-merge checks | ✅ 3 | ❌ 1 | ❓ 1

❌ Failed checks (1 warning, 1 inconclusive)

Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 56.52% which is insufficient. The required threshold is 80.00%. Docstring coverage is scoped to functions touched by this diff. Analyzed 23 functions across 6 files. Write docstrings for the functions missing them to satisfy the coverage threshold.
Linked Issues check ❓ Inconclusive For [#4672], the reported implementation extracts the algorithm into src/fl/gfx/binary_dither.h, keeps public PixelController::d[3] and e[3], forwards the existing methods, replaces the three ac… The complete test evidence for the byte-for-byte golden output requirement and the before/after image_flash results for all four AVR boards crossed with all three examples is not available.
✅ Passed checks (3 passed)
Check name Status Explanation
Description Check ✅ Passed Check skipped - CodeRabbit’s high-level summary is enabled.
Title check ✅ Passed The title clearly and concisely describes the main change: extracting binary dithering into a tested module that can be disabled with zero runtime cost.
Out of Scope Changes check ✅ Passed The reported whole-PR changes support [#4672]. They add the dither module and tests, forward PixelController methods, replace activity checks, clear disabled state, and remove the module's platform-…
Full details: Linked Issues check

Explanation

For [#4672], the reported implementation extracts the algorithm into src/fl/gfx/binary_dither.h, keeps public PixelController::d[3] and e[3], forwards the existing methods, replaces the three activity checks, and clears state in NoDither. The reported tests cover the algorithm, disabled behavior, and legacy initialization equivalence. The reported C++ tests and lint pass. The evidence does not establish the required byte-for-byte golden output test or image_flash results for all 12 AVR board/example combinations.

  • Fix all pre-merge checks with AI
✨ Finishing Touches 💡 1
📝 Generate docstrings 💡
  • Commit to this branch
  • Create a new PR
🧪 Generate unit tests (beta)
  • Commit to this branch
  • Create a new PR
  • Autopilot · Keep fixing CodeRabbit findings and required CI, and resolving merge conflicts

Autopilot is currently an internal CodeRabbit preview.


Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

❤️ Share

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

…er.h (#4672)

binary_dither.h included led_sysdefs.h to see NO_DITHERING, which reaches
fl/system/arduino.h -> <Arduino.h>. pixel_controller.h did not include that
before, so every unity TU reaching it parsed the full platform SDK -- more
compile memory on the ESP32 unity files that CI already OOM-kills (#4675).

Read NO_DITHERING the way the replaced code did (defined by FastLED.h ->
led_sysdefs.h before pixel_controller.h), and include binary_dither.h last
in pixel_controller.h. ATtiny still selects NoDither: attiny85 Blink/
ColorPalette sizes unchanged (3464/4822 B).
@zackees

zackees commented Oct 2, 2026 •

Copy link
Copy Markdown
Member Author

Pushed 989aeea: removed led_sysdefs.h from binary_dither.h. It dragged <Arduino.h>, and with it the ESP-IDF headers, into every unity TU that reaches pixel_controller.h, which that header did not do before. NO_DITHERING is read exactly as before (FastLED.h → led_sysdefs.h).

Correction: I first linked this include to the exit -9 kills on ESP32 unity TUs. Investigation under #4675 shows those kills are not OOM. Peak compile memory is about 2.2 GB on a 16 GB runner, and the kernel logged no OOM kill. The kills also happen on master and correlate with fbuild 2.5.30. The include removal is still correct, because pixel_controller.h should not pull in the platform SDK, but it is not the fix for those failures.

Sizes on the same base (current origin/master vs this branch, image_flash in bytes):

board / sketch master PR Δ
uno Blink 5178 5166 −12
uno Apa102 4522 4510 −12
attiny85 Apa102 3000 2882 −118
leonardo Blink 7106 7094 −12

@zackees
zackees merged commit 2975222 into master Oct 2, 2026
97 of 121 checks passed
@zackees
zackees deleted the refactor/binary-dither-module-4672 branch November 5, 2026 05:53
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

ci-full Run the complete release-equivalent CI matrix on this PR SHA

Projects

Status: Done

Development

Successfully merging this pull request may close these issues.

refactor(dither): extract binary dithering into a tested, zero-cost, disableable module (and fix uninitialised d/e under NO_DITHERING)

1 participant