Skip to content

perf(gamma): use fl::s16x16::pow for Gamma8 LUT + applyGamma_video; drop __ieee754_pow - #2911

Merged
zackees merged 1 commit into
masterfrom
feat/2910-gamma-powf
Jun 7, 2026
Merged

zackees merged 1 commit into
masterfrom
feat/2910-gamma-powf

Conversation

@zackees

@zackees zackees commented Jun 7, 2026 •

Copy link
Copy Markdown
Member

perf(gamma): use fl::s16x16::pow for Gamma8 LUT + applyGamma_video; drop __ieee754_pow

Closes #2910.

Replaces fl::pow(double, double) with fl::s16x16::pow (integer
fixed-point) in the two FastLED-owned callers that pull __ieee754_pow
(libm, 2,723 B in the post-#2908 audit) into release builds.

What changes

File Site Before After
src/fl/math/ease.cpp.hpp Gamma8Impl::Gamma8Impl(float) fl::pow(double, double) per LUT entry one fl::s16x16(gamma) ctor + per-entry fl::s16x16::pow
src/fl/gfx/colorutils.cpp.hpp applyGamma_video(u8, float) bare pow(orig, gamma) (float args → double) fl::s16x16::pow

fl::s16x16::pow is implemented as exp2_fp(exp * log2_fp(base))
where exp2_fp and log2_fp are pure integer LUT-based
implementations — zero libm dependency. The chain is broken at the
ctor / function entry: the public API still takes float gamma, but
that float is converted once to fl::s16x16 via the constexpr ctor
(one fmul + cast → __mulsf3 + __fixsfsi, both << 100 B).

Precision sanity-check

  • Gamma8Impl LUT is u16-valued. s16x16 has 16 fractional bits
    (~1.5×10⁻⁵ resolution) — well above the LUT's 16-bit output
    resolution.
  • applyGamma_video is u8 → u8. Same story.
  • Result is computed in [0, 1] then scaled to u16 / u8 with
    round-half-up via integer math:
    ((raw_u32 * scale) + 0x8000) >> 16.

Why s16x16 is enough

s16x16 is 16 integer + 16 fractional bits — range ~[-32768, 32767].

  • Gamma values are typically in [1.0, 4.0]: fits with massive headroom.
  • (i/255) is in [0, 1]: stored as raw [0, 65536].
  • Intermediate exp * log2_fp(base) for base ∈ (0, 1] and exp ∈ [1, 4]: log2(base) ∈ [-∞, 0], but s16x16::log2_fp clamps
    small inputs. The product stays in s16x16 range.
  • exp2_fp(...) returns [0, ~1] for the gamma case → fits.

Out of scope

  • third_party/cq_kernel/fft_precision.h — third-party FFT macro-driven.
  • third_party/stb/truetype/stb_truetype.cpp.hpp — third-party font rasterizer.
  • fl::pow fixed-point template specializations — different overloads, not affected.

Verification

  • bash lint --cpp → all C++ linting checks pass.
  • bash test --cpp fl/gfx/gamma_lut could not be run from the disposable
    PR worktree due to the known meson source-path bug at build(meson): bash test --cpp fails inside .claude/worktrees/ worktrees (Windows path / object-name encoding) #2887. The
    same diff applied to the main checkout will run on CI's
    unit tests linux job.
  • Behavior preserved (modulo ±1 LSB rounding from fixed-point vs
    double): Gamma8Impl LUT entries should match the original within
    rounding precision; applyGamma_video preserves the
    "never-down-to-zero" invariant via explicit result == 0 → 1.

Expected savings

  • Eliminated: __ieee754_pow (2,723 B).
  • Eliminated: any related double-math symbols only reachable via this path.
  • Added: __mulsf3, __fixsfsi (<< 100 B each — likely already
    linked by other float math sites).
  • Net: projected ~2-2.5 KB on the ESP32-S3 NEOPIXEL Blink build.

The Stage 6 regression gate (tests/test_esp32s3_bloat_regression.py,
baseline = 350127) validates the measurement on this PR's CI run. A
follow-up commit lowers the baseline file accordingly.

Refs #2886, #2910, #2908, #2909.

Summary by CodeRabbit

Release Notes

  • Refactor
    • Optimized gamma correction calculations in color utilities and image processing operations. These internal improvements enhance efficiency and consistency in color adjustments while maintaining identical visual output. The changes ensure reliable handling of color processing operations and brightness adjustments with consistent behavior across all scenarios.

…rop __ieee754_pow

Closes #2910.

Replaces `fl::pow(double, double)` with `fl::s16x16::pow` (integer
fixed-point) in the two FastLED-owned callers that pull `__ieee754_pow`
(libm, 2,723 B in the post-#2908 audit) into release builds.

## What changes

| File | Site | Before | After |
|---|---|---|---|
| `src/fl/math/ease.cpp.hpp` | `Gamma8Impl::Gamma8Impl(float)` | `fl::pow(double, double)` per LUT entry | one `fl::s16x16(gamma)` ctor + per-entry `fl::s16x16::pow` |
| `src/fl/gfx/colorutils.cpp.hpp` | `applyGamma_video(u8, float)` | bare `pow(orig, gamma)` (float args → double) | `fl::s16x16::pow` |

`fl::s16x16::pow` is implemented as `exp2_fp(exp * log2_fp(base))`
where `exp2_fp` and `log2_fp` are pure integer LUT-based
implementations — zero libm dependency. The chain is broken at the
ctor / function entry: the public API still takes `float gamma`, but
that float is converted once to `fl::s16x16` via the constexpr ctor
(one fmul + cast → `__mulsf3` + `__fixsfsi`, both << 100 B).

## Precision sanity-check

- `Gamma8Impl` LUT is u16-valued. `s16x16` has 16 fractional bits
  (~1.5×10⁻⁵ resolution) — well above the LUT's 16-bit output
  resolution.
- `applyGamma_video` is u8 → u8. Same story.
- Result is computed in [0, 1] then scaled to u16 / u8 with
  round-half-up via integer math:
  `((raw_u32 * scale) + 0x8000) >> 16`.

## Why s16x16 is enough

`s16x16` is 16 integer + 16 fractional bits — range ~[-32768, 32767].
- Gamma values are typically in [1.0, 4.0]: fits with massive headroom.
- `(i/255)` is in [0, 1]: stored as raw [0, 65536].
- Intermediate `exp * log2_fp(base)` for `base ∈ (0, 1]` and `exp ∈
  [1, 4]`: `log2(base) ∈ [-∞, 0]`, but `s16x16::log2_fp` clamps
  small inputs. The product stays in s16x16 range.
- `exp2_fp(...)` returns [0, ~1] for the gamma case → fits.

## Out of scope

- `third_party/cq_kernel/fft_precision.h` — third-party FFT macro-driven.
- `third_party/stb/truetype/stb_truetype.cpp.hpp` — third-party font rasterizer.
- `fl::pow` fixed-point template specializations — different overloads, not affected.

## Verification

- `bash lint --cpp` → all C++ linting checks pass.
- `bash test --cpp fl/gfx/gamma_lut` could not be run from the disposable
  PR worktree due to the known meson source-path bug at #2887. The
  same diff applied to the main checkout will run on CI's
  `unit tests linux` job.
- Behavior preserved (modulo ±1 LSB rounding from fixed-point vs
  double): `Gamma8Impl` LUT entries should match the original within
  rounding precision; `applyGamma_video` preserves the
  "never-down-to-zero" invariant via explicit `result == 0 → 1`.

## Expected savings

- Eliminated: `__ieee754_pow` (2,723 B).
- Eliminated: any related double-math symbols only reachable via this path.
- Added: `__mulsf3`, `__fixsfsi` (<< 100 B each — likely already
  linked by other float math sites).
- Net: projected ~2-2.5 KB on the ESP32-S3 NEOPIXEL Blink build.

The Stage 6 regression gate (`tests/test_esp32s3_bloat_regression.py`,
baseline = `350127`) validates the measurement on this PR's CI run. A
follow-up commit lowers the baseline file accordingly.

Refs #2886, #2910, #2908, #2909.
@coderabbitai

coderabbitai Bot commented Jun 7, 2026 •

Copy link
Copy Markdown

Review Change Stack

Caution

Review failed

The pull request is closed.

ℹ️ Recent review info
⚙️ Run configuration

Configuration used: Path: .coderabbit.yaml

Review profile: CHILL

Plan: Pro

Run ID: 8d71104e-913b-4d7c-a1ad-761aa89e9cb1

📥 Commits

Reviewing files that changed from the base of the PR and between 780ab73 and 93b5ae4.

📒 Files selected for processing (2)
  • src/fl/gfx/colorutils.cpp.hpp
  • src/fl/math/ease.cpp.hpp

📝 Walkthrough

Walkthrough

Two gamma-application functions—applyGamma_video in colorutils and Gamma8Impl's LUT constructor in ease—are rewritten from floating-point (libm-dependent) to fixed-point (fl::s16x16) arithmetic. The scalar path includes edge-case preservation; the LUT path replaces double-based rounding with integer scaling. No exported signatures change.

Changes

Fixed-point gamma arithmetic

Layer / File(s) Summary
Fixed-point gamma in applyGamma_video
src/fl/gfx/colorutils.cpp.hpp
applyGamma_video(fl::u8, float) now uses fl::s16x16 fixed-point pow and scaled rounding instead of floating-point operations; fl/math/fixed_point.h is included, and edge cases (brightness==0 → 0, positive brightness adjusting to zero → clamped to 1) are preserved.
Fixed-point gamma in Gamma8Impl LUT generation
src/fl/math/ease.cpp.hpp
Gamma8Impl::Gamma8Impl(float) builds the 256-entry u16 LUT via fl::s16x16 fixed-point exponentiation and integer scaling, replacing double-based fl::pow + fl::round and removing libm dependency during LUT initialization.

🎯 3 (Moderate) | ⏱️ ~18 minutes

🐰 Two gamma paths now hop in fixed-point shoes,
No more libm pow, the release builds can't lose!
Precision enough for the palette we know,
Integer rounding makes tiny code grow—
— Hoppy Refactor Rabbit ✨

✨ Finishing Touches
📝 Generate docstrings
  • Create stacked PR
  • Commit on current branch
🧪 Generate unit tests (beta)
  • Create PR with unit tests
  • Commit unit tests in branch feat/2910-gamma-powf

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 and usage tips.

@zackees
zackees merged commit f090358 into master Jun 7, 2026
6 of 8 checks passed
zackees added a commit that referenced this pull request Jun 7, 2026
…6::pow) (#2912)

Measured against `master @ f090358` (PR #2911 just merged):

    Total flash: 347,004 B  (3,621 sized flash symbols).  RAM: 37,389 B.
    (was: 350,127 B / 3,627 symbols / 37,453 B RAM on master @ 731e4d5)

Delta: -3,123 B flash / -6 symbols / -64 B RAM. The dropped symbols are
the double-precision pow chain that was only reachable via Gamma8Impl
and applyGamma_video:

  - __ieee754_pow (was 2,723 B / top-9)
  - + supporting double-math machinery only reachable from those callers

The fixed-point path (fl::s16x16::pow) is pure integer LUT and pulls
zero new libm symbols. Note that __ieee754_pow is no longer on the
top-10; uartBegin moved up to #9.

Refs #2886, #2910, #2911.
@fastled-project-sync fastled-project-sync Bot moved this to Triage in FastLED Tracker Jun 7, 2026
@fastled-project-sync fastled-project-sync Bot moved this from Triage to Done in FastLED Tracker Jun 7, 2026
zackees added a commit that referenced this pull request Jun 7, 2026
…DISABLE_SPI_CHIPSETS (#2914)

Closes #2913.

Adds an opt-in build flag `FASTLED_DISABLE_SPI_CHIPSETS=1` that gates
the SPI dispatch branch in `fl::Channel::showPixels`. For NEOPIXEL-only
sketches the SPI branch is dynamically unreachable, but the compiler
cannot prove that — every `pixelIterator.writeXXX(...)` reference
inside the 11-case switch is statically reachable, keeping ~720 B of
encoder bodies and the switch-table footprint linked.

## Measured baseline (post-#2911, `master @ 6bd4ebd`)

Dead-code SPI encoder symbols currently linked into a NEOPIXEL Blink:

| Symbol | Size |
|---|---:|
| `fl::PixelIterator::writeLPD8806<fl::vector_psram<u8>>` | 235 B |
| `fl::PixelIterator::writeSK9822<fl::vector_psram<u8>>` | 197 B |
| `fl::PixelIterator::writeAPA102<fl::vector_psram<u8>>` | 197 B |
| `fl::PixelIterator::writeSM16716<fl::vector_psram<u8>>` | 91 B |
| **Total** | **720 B** |

Plus the `showPixels` body itself shrinks by the switch-table footprint
(~300-500 B for an 11-case xtensa switch). Projected total saving:
**~1.0-1.2 KB** on a NEOPIXEL Blink build with the flag enabled.

## Behavior

- **Flag unset (default):** No change. The SPI dispatch is present;
  every existing example using APA102 / SK9822 / etc. continues to
  work.
- **Flag set (`-DFASTLED_DISABLE_SPI_CHIPSETS=1`):** The SPI branch is
  removed at preprocess time. `showPixels()` on a channel whose
  chipset is an `SpiChipsetConfig` falls through to the post-dispatch
  event emission with no data encoded — the channel silently emits
  nothing. Users opt in with the understanding that they're not
  using SPI chipsets in this build.

This mirrors the opt-in build-flag pattern shipped in #2894
(Stage 2 / boot-banner shim) — minimal default-change risk, real
savings for users who can accept the constraint.

## Files

- `src/fl/channels/channel.cpp.hpp` — `#if !defined(FASTLED_DISABLE_SPI_CHIPSETS) || !FASTLED_DISABLE_SPI_CHIPSETS`
  wraps the `else if (mChipset.is<SpiChipsetConfig>())` block. The
  gate's behavior + savings are documented inline at the comment block
  above the branch.
- `docs/SLIM_ESP32S3.md` — adds row 6 to the "Release-build flash
  savers" priority table with the new flag, its constraint, and PR
  link.

## Verification

- `bash lint --cpp` → all C++ linting checks pass.
- The flag follows the established opt-in pattern; default behavior
  unchanged.
- Measured saving will be validated on the post-merge build (a
  `-DFASTLED_DISABLE_SPI_CHIPSETS=1` build of Blink, compared against
  the current `347,004 B` baseline).

## Expected savings

- Eliminated: writeAPA102 (197 B), writeSK9822 (197 B), writeLPD8806
  (235 B), writeSM16716 (91 B) = 720 B (PixelIterator SPI encoders
  reachable only from showPixels' SPI branch).
- Eliminated: ~300-500 B of switch-table + dispatch code in
  `showPixels` body.
- Net: ~1.0-1.2 KB projected on NEOPIXEL Blink with flag set.

The Stage 6 regression gate (`tests/test_esp32s3_bloat_regression.py`,
baseline = `347004`) does NOT change in this PR because it measures
the default-flag build, which is unchanged. A separate follow-up
records the flag-on measured number once a measurement run lands.

Refs #2886, #2913, #2908, #2911.
zackees added a commit that referenced this pull request Jun 7, 2026
…rlay (#2916)

Closes #2915.

Adds the biggest missing single lever to the Stage 3 overlay file
shipped in #2896. The standard newlib printf cluster — `_vfprintf_r`
(11.3 KB), `_svfprintf_r` (11.1 KB), `_svfiprintf_r` (7.3 KB),
`_vfiprintf_r` (7.3 KB), `_dtoa_r` (3.2 KB), `get_arg$isra$0` copies
(4.9 KB cumulative) — collectively eats **~45 KB** on the post-#2911
ESP32-S3 NEOPIXEL Blink baseline (the largest non-FastLED cluster in
the audit). Nano newlib drops it by 50-70%.

## Why this was missed

The Stage 3 overlay #2896 targeted four sub-1.5 KB symbol clusters
(coredump, IDF diag log, bootloader chatter, panic formatter) but
left the dominant ~45 KB libc printf cluster unattended. Adding
`CONFIG_NEWLIB_NANO_FORMAT=y` is a one-line config flip that's a
larger lever than every other Stage 3 knob combined.

## The constraint

Nano newlib printf has no `%f` / `%lf` / `%lld` / positional-arg
support. Sketches that print floating-point values via printf will
see literal format specifiers in the output instead of the formatted
number. For LED installations this is rarely an issue — strip
control code doesn't typically log floats. For sketches that DO need
extended formats, the user either drops the overlay entirely or
layers their own sdkconfig with `CONFIG_NEWLIB_NANO_FORMAT=n` after
FastLED's.

## Files

- `tools/sdkconfig_for_smallest_fastled.defaults` — new entry with
  inline constraint documentation, placed in the "Conservative knobs"
  section (it qualifies because most LED installations don't print
  floats).
- `docs/SLIM_ESP32S3.md` — row 2 of the priority table updated from
  `~10-15 KB` → `~30-45 KB`. Stage 3 detail section's knob table
  expanded from 4 → 5 rows with the nano-newlib entry at the top,
  plus a new constraint sidebar.
- `agents/docs/binary-size-analysis.md` — agent-facing copy of the
  priority table mirrors the SLIM doc update.

## Verification

- `bash lint --cpp` → all C++ linting checks pass (this PR doesn't
  touch C++).
- The overlay file remains opt-in (users must wire it into
  `board_build.sdkconfig_defaults` themselves). Default behavior is
  unchanged for users who haven't already chosen the overlay.
- Measured savings will be validated on a follow-up build with the
  overlay applied. Expected: ~20-30 KB drop in `total_flash` vs
  current baseline (`347,004 B`).

## Expected savings

- Pre-overlay (Stage 1 only): 347,004 B (current measured baseline).
- Post-overlay (Stages 1+3 with nano printf):
  ≈ 347,004 - 25,000 = ~322,000 B (projected).
- Gap to #2886 end-goal (280,000 B): ~42 KB remaining,
  most of which lives in #2856 (structural meta).

The Stage 6 regression gate baseline does NOT change in this PR
(the default-flag build is unchanged). A follow-up PR records the
measured number after a build with the overlay applied.

Refs #2886, #2915, #2896, #2906.
zackees added a commit that referenced this pull request Jun 7, 2026
…dies on FASTLED_LOG_RUNTIME_ENABLED (#2918)

Closes #2917.

Wraps the bodies of the two `FL_NO_INLINE` cold-path emit helpers in
`fl::ChannelEngineRMTImpl` with `#if FASTLED_LOG_RUNTIME_ENABLED`. In
release builds (NDEBUG → `FASTLED_LOG_VERBOSITY=0` per Stage 1) the
helpers collapse to ~5 B function bodies (parameters cast to `(void)`,
single `ret`), down from ~410-418 B each.

## Why the existing FL_NO_INLINE + FL_WARN pattern wasn't enough

```cpp
FL_NO_INLINE void emitRecoveryWarning(...) FL_NOEXCEPT {
    fl::sstream msg;                          // [1] constructed unconditionally
    msg << "..." << ... << external_words;    // [2] 15 operator<< calls fire
    FL_WARN(msg.str());                       // [3] expands to no-op in release
}
```

In release builds:
- `FL_WARN(X)` expands to `do { if (false) { ... << X; } } while(0)` —
  optimizer DCEs the inner block (`msg.str()` call elided).
- But `fl::sstream msg;` at [1] and `msg << ...` at [2] are **outside**
  the `if (false)` block. They have observable side effects on `msg`'s
  internal buffer (heap allocation, sequential writes), so the optimizer
  keeps the constructor + all 15 `operator<<` calls live in the function
  body.

Result: the FL_NO_INLINE pulled the diagnostic chain out of the
function it was hoisted from (`createChannel`) — into its own symbol
— but the bytes stayed in the binary.

## Measured baseline (post-#2916 ELF, `master @ 5ca722e`)

| Symbol | Size |
|---|---:|
| `fl::ChannelEngineRMTImpl::emitAllocationFailureError` (`$isra$0`) | 418 B |
| `fl::ChannelEngineRMTImpl::emitRecoveryWarning` (`$isra$0`) | 410 B |
| **Total in scope** | **~828 B** |

Both symbols collapse to ~5 B after this PR.

## Behavior preserved

- **Debug builds (`FASTLED_LOG_VERBOSITY=1`, default for non-NDEBUG):**
  the diagnostic emits exactly as before. Users debugging RMT
  allocation failures still see the multi-line action-required
  message.
- **Release builds (`FASTLED_LOG_VERBOSITY=0`, NDEBUG default since
  #2890):** the helper bodies become empty; the callers in
  `attemptAllocationRecovery` still call them (the call overhead is
  ~5 B / site), but the bodies cost nothing.

The FL_WARN macro itself was always a no-op in release; this PR makes
the body that *built the message* match the macro's release-build
behavior.

## Other emit helpers — audit notes

- `attemptAllocationRecovery` (315 B total): contains its own FL_WARN
  and FL_LOG_RMT calls plus actual retry-loop arithmetic. The
  diagnostic calls go through the standard `FL_WARN` macro which is
  already `do { if (false) { ... } } while(0)` in release — the
  optimizer DCEs the inline chain. The 315 B is the retry-loop body
  + `Rmt5ChannelConfig retry_config(...)` construction; NOT the
  diagnostic emission. Leaving as-is.
- `handleAllocateTxFailure` (63 B): already a `FL_NO_INLINE` cold
  helper at 63 B post-Stage-1 — almost entirely the fallback retry
  body. No further gating needed.

## Out of scope

- Removing the FL_WARN calls from the source. They're useful in debug
  builds; the gate keeps them debug-build-active.
- Auditing every FL_WARN call site in the RMT5 driver — the inline
  ones inside hot function bodies are already collapsed correctly by
  the `if (false)` DCE.

## Verification

- `bash lint --cpp` → all C++ linting checks pass.
- Behavior preserved by construction: the gate is on a build-time
  define that defaults to "diagnostics on" in debug builds.
- Measured saving validated on this PR's CI run via the Stage 6
  regression gate. Expected: `total_flash` drops by ~700-800 B from
  the current baseline of `347,004 B`. A follow-up commit ratchets
  the baseline file in the same PR.

Refs #2886, #2917, #2908, #2911, #2914.
zackees added a commit that referenced this pull request Jun 7, 2026
…che (#2929)

Closes #2928.

Replaces `fl::flat_map<GammaKey, fl::weak_ptr<const Gamma8>>` with a
single-entry weak_ptr cache. For the stock `addLeds<NEOPIXEL>` /
every other legacy flow, a single fixed gamma value (typically 2.8)
is reused for the lifetime of the sketch — the flat_map's multi-entry
machinery (insert, find, key compare, vector growth) is pure overhead
for that case.

## Behavior matrix

| Scenario | Before (flat_map) | After (single-entry) |
|---|---|---|
| First call with gamma X | Allocate, cache. | Allocate, cache. |
| Repeated call with same gamma X (alive) | Return cached. | Return cached. |
| Call with new gamma Y (X still alive) | Cache both. | Cache replaced with Y. |
| Call after all references dropped | Reallocate. | Reallocate. |

Users who switch gamma values at runtime pay one extra `Gamma8Impl`
reconstruction per switch (256 fixed-point pow operations + ~512 B
alloc). Rare scenario; negligible cost.

## Files

- src/fl/math/ease.cpp.hpp: getOrCreate body rewritten to use 3
  function-scoped statics (GammaKey, weak_ptr, bool) instead of the
  flat_map template instantiation. Comment updated to reference
  #2928.

## Verification

- bash lint --cpp -> all C++ linting checks pass.
- Behavior preserved for the single-gamma case (the only case in
  stock `addLeds<>` flows).

## Expected savings

Projected ~200-400 B on the ESP32-S3 NEOPIXEL Blink build. The
flat_map template instantiation pulled in its vector-backed sorted-
storage, key-comparison logic, and `fl::pair<GammaKey, weak_ptr>`
element type. All of those become dead code with the single-entry
replacement.

The Stage 6 regression gate (tests/test_esp32s3_bloat_regression.py,
baseline = 340832) will validate the measurement; a follow-up commit
ratchets the baseline file if positive.

Refs #2886, #2928, #2911.
@zackees
zackees deleted the feat/2910-gamma-powf branch August 21, 2026 19:15
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

Status: Done

Development

Successfully merging this pull request may close these issues.

Drop __ieee754_pow (2.7 KB) via fl::powf in Gamma8Impl + applyGamma_video (#2886)

1 participant