Skip to content

feat(rgbw): colorimetric solvers + LUT + CCT + RGBCCT (full #2545) - #2552

Merged
zackees merged 1 commit into
masterfrom
feat/rgbw-colorimetric
May 30, 2026
Merged

zackees merged 1 commit into
masterfrom
feat/rgbw-colorimetric

Conversation

@zackees

@zackees zackees commented May 30, 2026 •

Copy link
Copy Markdown
Member

Summary

Single squashed commit implementing all phases of #2545:

Phase 1 — runtime colorimetric solvers

Two new RGBW_MODE variants gated behind FASTLED_RGBW_COLORIMETRIC:

  • kRGBWColorimetric — strict sub-gamut solver (gist §5). Routes target chromaticity to RGW/RBW/BGW, solves 3×3.
  • kRGBWColorimetricBoosted — wx_lp_legacy overdrive (gist §9). Closed-form scalar LP, maximizes W subject to RGB ≥ 0.

Stub path (gate undefined) tail-calls rgb_2_rgbw_exact after a one-time FL_WARN_ONCE. Suppress via FASTLED_SUPPRESS_COLORIMETRIC_FALLBACK_WARNING.

Phase 2a — Rgbw::white_color_temp finally does something

DiodeProfile gains a nominal_cct field. When the dispatch is called with a w_color_temperature that differs from the profile's nominal CCT, the W vertex chromaticity is shifted via Krystek's blackbody approximation (cct_to_xy, valid 1500K–15000K). Cache is keyed on (profile, cct) so the shift is precomputed once.

Phase 2b — 2D + 1D factored LUT (FASTLED_RGBW_COLORIMETRIC_LUT)

Optional LUT path gated behind a second compile flag. Lookup = bilinear-interpolated xy grid (4 channels per cell, int16 quantized at 4096) × Y_t, with the same brightness-normalization as the closed-form path. Rebuilt automatically when the active profile or CCT changes.

fl::enable_rgbw_colorimetric_lut(32);   // ~8 KB, sub-0.25 dE mean vs closed-form
// ... colorimetric calls now go through the LUT ...
fl::disable_rgbw_colorimetric_lut();

Public API is link-safe even when the flag is off (returns false / no-ops).

Phase 3 — RGBCCT 5-channel helper

RgbcctProfile (two DiodeProfiles, warm + cool W) and solve_rgbcct() in fl/gfx/rgbw_colorimetric.h provide the layered-simplex math per gist §§11–12: solve target against each W diode, then line-blend the resulting RGBW tuples by an eta ∈ [0, 1]. rgbcct_eta_for_cct() derives eta from a target CCT vs the warm/cool reference CCTs.

Stays a header helper rather than a new RGBW_MODE because the existing dispatch returns 4 channels; multi-channel public dispatch is left for when there's a concrete 5-channel chipset wired through the rest of FastLED's pipeline.

Design notes

  • Per-pixel solver math (xyY↔XYZ, 3×3 invert, barycentric containment, strict subgamut, wx_lp, LUT lookup, RGBCCT blend) lives as inline functions in fl/gfx/rgbw_colorimetric.h so tests can validate algorithms directly regardless of how the library was built.
  • Library-side dispatch in rgbw.cpp.hpp owns the lazy Singleton<ColorimetricCacheHolder> and Singleton<LutStateHolder> state — zero static-init cost when no colorimetric mode is invoked.
  • kRGBWUserFunction is documented as required-last in the enum (the dispatch table relies on it being the max value).

Test plan

  • fl_gfx_rgbw_colorimetric test suite (17 cases): math round-trips, profile cache, strict subgamut + wx_lp correctness, Krystek vs published Planckian-locus values at 2700/4000/6500K, CCT-driven W shift, LUT accuracy vs closed-form (max xy error < 0.01 at N=32), public-API stub fallback, LUT enable/disable link safety, RGBCCT chromaticity preservation across warm↔cool blend, rgbcct_eta_for_cct linear interp.
  • Full host test suite: 306/306 passing.
  • Manual hardware verification with -DFASTLED_RGBW_COLORIMETRIC=1 against a real RGBW strip + colorimeter (left for follow-up; reference data in feat(rgbw): sub-gamut white-extraction algorithm for chromaticity-accurate RGBW output #2545).

🤖 Generated with Claude Code

Summary by CodeRabbit

  • New Features

    • Two chromaticity-aware RGBW modes (including boosted) for improved RGB→RGBW conversion
    • Selectable diode colorimetric profile with a documented default and public get/set controls
    • Optional colorimetric LUT pathway that can be enabled/disabled for faster lookups
    • CCT-aware blending and full 5‑channel RGBCCT support
  • Tests

    • Expanded unit tests covering colorimetric math, LUT pipeline, profile get/set, and RGBCCT behavior

Review Change Stack

@coderabbitai

coderabbitai Bot commented May 30, 2026 •

Copy link
Copy Markdown

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: 164bc652-39e3-4de7-ad46-4eb6b790b853

📥 Commits

Reviewing files that changed from the base of the PR and between a0d0ed7 and 5b1cac5.

📒 Files selected for processing (7)
  • src/fl/gfx/_build.cpp.hpp
  • src/fl/gfx/rgbw.cpp.hpp
  • src/fl/gfx/rgbw.h
  • src/fl/gfx/rgbw_colorimetric.cpp.hpp
  • src/fl/gfx/rgbw_colorimetric.h
  • src/rgbw.h
  • tests/fl/gfx/rgbw_colorimetric.cpp

📝 Walkthrough

Walkthrough

Adds DiodeProfile-driven chromaticity-aware RGB→RGBW solvers (strict subgamut and wx_lp), per-process profile caching with optional CCT override, optional LUT acceleration, public APIs for profile and LUT control, backward-compatible aliases, and comprehensive unit tests.

Changes

RGBW Colorimetric Output

Layer / File(s) Summary
Public API contract
src/fl/gfx/rgbw.h, src/rgbw.h
DiodeProfile struct, new RGBW_MODE values (kRGBWColorimetric, kRGBWColorimetricBoosted), profile getter/setter, LUT control APIs, conversion function declarations, and inline dispatcher routing.
Default profile & state
src/fl/gfx/rgbw.cpp.hpp
Defines kRgbwDefaultProfile, lazy per-process profile state, and cache-keying on profile pointer + effective CCT override.
Conversion implementations & LUT control
src/fl/gfx/rgbw.cpp.hpp
Implements rgb_2_rgbw_colorimetric and _boosted (black fast-path, strict solve with fallback, quantization), optional LUT fast-path with lazy rebuild and allocator-backed storage, LUT enable/disable/rebuild lifecycle, and disabled-feature stubs that warn-once and fall back to exact conversion.
Colorimetric math & solvers
src/fl/gfx/rgbw_colorimetric.h, src/fl/gfx/rgbw_colorimetric.cpp.hpp
Header-only primitives (cct_to_xy, xyY_to_XYZ, matrix ops, barycentric), ProfileCache with optional CCT override, solve_strict_subgamut/solve_strict_subgamut_xy, solve_wx_lp, LUT build/lookup and quantization, and RGBCCT 5-channel helpers (solve_rgbcct, rgbcct_eta_for_cct).
Backward compatibility
src/rgbw.h
Top-level constexpr aliases for the new colorimetric modes to preserve legacy code.
Tests
tests/fl/gfx/rgbw_colorimetric.cpp
Unit tests for math primitives, solvers, LUT correctness, CCT helpers, RGBCCT blending, profile get/set, and API dispatch/link-safety.

Sequence Diagram

sequenceDiagram
  participant App as Application
  participant Dispatch as rgb_2_rgbw (dispatcher)
  participant Convert as rgb_2_rgbw_colorimetric
  participant Cache as ProfileCacheHolder
  participant Solver as solve_strict_subgamut / solve_wx_lp
  participant LUT as colorimetric LUT
  participant Quant as quantize_u8

  App->>Dispatch: RGB(r,g,b), mode=kRGBWColorimetric
  Dispatch->>Convert: forward RGB + active profile pointer
  Convert->>Cache: check/rebuild cache (profile pointer / cct_override)
  alt LUT enabled
    Convert->>LUT: lookup_lut(xy,Y)
    LUT-->>Convert: float RGBW
  else LUT disabled
    Convert->>Solver: solve_strict_subgamut(s_r,s_g,s_b)
    alt strict failed
      Convert->>Solver: solve_wx_lp(s_r,s_g,s_b)
    end
    Solver-->>Convert: float RGBW
  end
  Convert->>Quant: quantize_u8(float RGBW)
  Quant-->>App: u8[4] RGBW
Loading

Estimated code review effort

🎯 4 (Complex) | ⏱️ ~45 minutes

Possibly related issues

Poem

🐰 I hopped through xy and into XYZ,
Tuned white points and cached the profiles for me.
Barycentric leaps and LUTs in store,
Warm and cool blend, five channels roar.
Now RGBW sings chroma forevermore.

🚥 Pre-merge checks | ✅ 4 | ❌ 1

❌ Failed checks (1 warning)

Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 31.82% which is insufficient. The required threshold is 80.00%. Write docstrings for the functions missing them to satisfy the coverage threshold.
✅ 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: it introduces colorimetric solvers, LUT support, CCT (color temperature), and RGBCCT functionality for RGBW color handling, which aligns with the substantial additions across multiple header and implementation files.
Linked Issues check ✅ Passed Check skipped because no linked issues were found for this pull request.
Out of Scope Changes check ✅ Passed Check skipped because no linked issues were found for this pull request.

✏️ Tip: You can configure your own custom pre-merge checks in the settings.

✨ 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/rgbw-colorimetric

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.

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 2

🧹 Nitpick comments (3)
src/fl/gfx/rgbw_colorimetric.h (2)

16-75: ⚖️ Poor tradeoff

Consider using fl::span<T> for array parameters.

The math utility functions (xyY_to_XYZ, invert3x3, matvec3, barycentric_xy) use raw array parameters. As per coding guidelines, "Use fl::span for function parameters instead of fl::vector or raw arrays."

Example for xyY_to_XYZ:

inline void xyY_to_XYZ(float x, float y, float Y, fl::span<float> out) FL_NOEXCEPT {
    // Add size check: out.size() >= 3
    // ...
}
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@src/fl/gfx/rgbw_colorimetric.h` around lines 16 - 75, The functions
xyY_to_XYZ, invert3x3, matvec3 and barycentric_xy take raw C arrays and should
be converted to fl::span parameters (e.g., fl::span<float> out for 3-element
vectors and fl::span<const float> in for inputs) per the guideline; update each
signature to use fl::span (or fl::span<const T> for read-only inputs), add
runtime size checks (out.size() >= 3, in.size() >= 9 or pass a span of 3 spans
for 3x3) and return false or assert on bad size, include the fl::span header,
and update all call sites to pass spans (or &array[0] wrapped as span)
accordingly to ensure correctness for xyY_to_XYZ, invert3x3, matvec3 and
barycentric_xy.

7-7: 💤 Low value

Consider using FastLED compiler control macros instead of raw #pragma.

As per coding guidelines, "Use FastLED compiler control macros from fl/stl/compiler_control.h instead of raw #pragma directives."

🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@src/fl/gfx/rgbw_colorimetric.h` at line 7, Replace the raw `#pragma once` in
rgbw_colorimetric.h with the FastLED compiler control macros by including
fl/stl/compiler_control.h and wrapping the header with the provided header-guard
macros (i.e., use the header guard begin/end macros from that header instead of
`#pragma once`) so the file uses the project's compiler control macros rather
than a raw pragma.
tests/fl/gfx/rgbw_colorimetric.cpp (1)

23-30: 💤 Low value

Consider using fl::span for array parameters.

The helper functions use raw C-style arrays (const float rgbw[4], float out[3]) without compile-time size information. While acceptable for local test helpers, using fl::span<const float, 4> and fl::span<float, 3> would provide stronger type safety and make array sizes explicit. The same pattern appears in target_XYZ (lines 32-37) and to_xy (lines 40-46).

🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@tests/fl/gfx/rgbw_colorimetric.cpp` around lines 23 - 30, The helper
functions rgbw_to_XYZ, target_XYZ, and to_xy use raw C-style arrays (e.g., const
float rgbw[4], float out[3]) which lack compile-time size safety; replace those
parameters with fl::span<const float, 4> and fl::span<float, 3> (or
fl::span<const float, 3>/fl::span<float, 2> as appropriate for each function) to
make sizes explicit and safer, update the function signatures and all call sites
accordingly, and include the appropriate header for fl::span so the code
compiles.
🤖 Prompt for all review comments with AI agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

Inline comments:
In `@src/fl/gfx/rgbw_colorimetric.h`:
- Around line 109-112: The four calls to invert3x3 (for P_RGB, P_RGW, P_RBW,
P_BGW) are unchecked and can leave cache->P_*_inv garbage on failure; update
build_profile_cache to check each invert3x3 return value and abort on any
failure (free/clean partial state as needed) and propagate an error (e.g.,
change build_profile_cache to return bool or an error code) so callers can
detect a singular matrix; reference the specific symbols invert3x3 and
build_profile_cache and ensure cache->P_*_inv is not used unless the
corresponding invert3x3 succeeded.

In `@tests/fl/gfx/rgbw_colorimetric.cpp`:
- Around line 251-269: The test's name/comments promise that the stub fallback
equals rgb_2_rgbw_exact but the assertions only check byte ranges; update the
FL_TEST_CASE so it calls rgb_2_rgbw and rgb_2_rgbw_exact with the same inputs
(use RGBW_MODE::kRGBWColorimetric, kRGBWDefaultColorTemp and the same RGB/min
values used) and then: if the two outputs match exactly assert equality
(r_out,g_out,b_out,w_out == r_exact,g_exact,b_exact,w_exact), otherwise fall
back to asserting each byte is in [0,255]; keep references to the existing
function names rgb_2_rgbw and rgb_2_rgbw_exact and the test case symbol
FL_TEST_CASE (or alternatively rename the test to reflect "returns valid bytes"
if you prefer the simpler change).

---

Nitpick comments:
In `@src/fl/gfx/rgbw_colorimetric.h`:
- Around line 16-75: The functions xyY_to_XYZ, invert3x3, matvec3 and
barycentric_xy take raw C arrays and should be converted to fl::span parameters
(e.g., fl::span<float> out for 3-element vectors and fl::span<const float> in
for inputs) per the guideline; update each signature to use fl::span (or
fl::span<const T> for read-only inputs), add runtime size checks (out.size() >=
3, in.size() >= 9 or pass a span of 3 spans for 3x3) and return false or assert
on bad size, include the fl::span header, and update all call sites to pass
spans (or &array[0] wrapped as span) accordingly to ensure correctness for
xyY_to_XYZ, invert3x3, matvec3 and barycentric_xy.
- Line 7: Replace the raw `#pragma once` in rgbw_colorimetric.h with the FastLED
compiler control macros by including fl/stl/compiler_control.h and wrapping the
header with the provided header-guard macros (i.e., use the header guard
begin/end macros from that header instead of `#pragma once`) so the file uses
the project's compiler control macros rather than a raw pragma.

In `@tests/fl/gfx/rgbw_colorimetric.cpp`:
- Around line 23-30: The helper functions rgbw_to_XYZ, target_XYZ, and to_xy use
raw C-style arrays (e.g., const float rgbw[4], float out[3]) which lack
compile-time size safety; replace those parameters with fl::span<const float, 4>
and fl::span<float, 3> (or fl::span<const float, 3>/fl::span<float, 2> as
appropriate for each function) to make sizes explicit and safer, update the
function signatures and all call sites accordingly, and include the appropriate
header for fl::span so the code compiles.
🪄 Autofix (Beta)

Fix all unresolved CodeRabbit comments on this PR:

  • Push a commit to this branch (recommended)
  • Create a new PR with the fixes

ℹ️ Review info
⚙️ Run configuration

Configuration used: Path: .coderabbit.yaml

Review profile: CHILL

Plan: Pro

Run ID: 6e12fcc7-8877-4dea-81f2-155b19a516cd

📥 Commits

Reviewing files that changed from the base of the PR and between 99e75b3 and b1d4a5e.

📒 Files selected for processing (5)
  • src/fl/gfx/rgbw.cpp.hpp
  • src/fl/gfx/rgbw.h
  • src/fl/gfx/rgbw_colorimetric.h
  • src/rgbw.h
  • tests/fl/gfx/rgbw_colorimetric.cpp

Comment thread src/fl/gfx/rgbw_colorimetric.h Outdated
Comment on lines +109 to +112
invert3x3(P_RGB, cache->P_RGB_inv);
invert3x3(P_RGW, cache->P_RGW_inv);
invert3x3(P_RBW, cache->P_RBW_inv);
invert3x3(P_BGW, cache->P_BGW_inv);

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

⚠️ Potential issue | 🔴 Critical | ⚡ Quick win

Check return values from invert3x3 to prevent silent corruption.

build_profile_cache calls invert3x3 four times without checking the return values. If any matrix is singular or near-singular (e.g., from malformed profile data), the inversion fails and the cache contains garbage, corrupting all subsequent color conversions.

🛡️ Proposed fix to validate matrix inversions
-    invert3x3(P_RGB, cache->P_RGB_inv);
-    invert3x3(P_RGW, cache->P_RGW_inv);
-    invert3x3(P_RBW, cache->P_RBW_inv);
-    invert3x3(P_BGW, cache->P_BGW_inv);
+    if (!invert3x3(P_RGB, cache->P_RGB_inv) ||
+        !invert3x3(P_RGW, cache->P_RGW_inv) ||
+        !invert3x3(P_RBW, cache->P_RBW_inv) ||
+        !invert3x3(P_BGW, cache->P_BGW_inv)) {
+        // Matrix inversion failed - profile is degenerate.
+        // Zero out cache to signal failure or FL_WARN and use safe defaults.
+        FL_WARN("RGBW profile matrix inversion failed - degenerate primaries");
+    }

Alternatively, modify build_profile_cache to return bool so callers can detect and handle the failure appropriately.

🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@src/fl/gfx/rgbw_colorimetric.h` around lines 109 - 112, The four calls to
invert3x3 (for P_RGB, P_RGW, P_RBW, P_BGW) are unchecked and can leave
cache->P_*_inv garbage on failure; update build_profile_cache to check each
invert3x3 return value and abort on any failure (free/clean partial state as
needed) and propagate an error (e.g., change build_profile_cache to return bool
or an error code) so callers can detect a singular matrix; reference the
specific symbols invert3x3 and build_profile_cache and ensure cache->P_*_inv is
not used unless the corresponding invert3x3 succeeded.

Comment thread tests/fl/gfx/rgbw_colorimetric.cpp Outdated
Comment on lines +251 to +269
FL_TEST_CASE("public API stub fallback matches rgb_2_rgbw_exact when colorimetric not in lib") {
// The library may have been built with or without FASTLED_RGBW_COLORIMETRIC.
// When without: stub falls back to rgb_2_rgbw_exact and the output is
// byte-for-byte identical. When with: real path runs and may differ.
// Test the stub path semantics: select kRGBWColorimetric, verify the
// output is at least sensible (not garbage, all channels in [0, 255]).
u8 r_out, g_out, b_out, w_out;
rgb_2_rgbw(RGBW_MODE::kRGBWColorimetric, kRGBWDefaultColorTemp,
200, 100, 50, 255, 255, 255,
&r_out, &g_out, &b_out, &w_out);
// Smoke test: no UB, output bytes are valid. Either:
// stub path -> equals rgb_2_rgbw_exact: (R-min, G-min, B-min, min)
// = (200-50, 100-50, 50-50, 50) = (150, 50, 0, 50)
// real path -> some chromaticity-accurate tuple, all in [0, 255].
FL_CHECK(r_out <= 255);
FL_CHECK(g_out <= 255);
FL_CHECK(b_out <= 255);
FL_CHECK(w_out <= 255);
}

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

⚠️ Potential issue | 🟡 Minor | ⚡ Quick win

Test name and comments don't match assertions.

The test name claims "stub fallback matches rgb_2_rgbw_exact" and lines 262-264 document exact expected values (150, 50, 0, 50), but the test only verifies outputs are in [0, 255] range. This doesn't validate the documented equality contract. Either:

  1. Strengthen the test to call both functions and compare when the stub path is active, or
  2. Rename to "public API returns valid bytes" and remove the equality claim from comments.
🔍 Proposed fix to strengthen the test
 FL_TEST_CASE("public API stub fallback matches rgb_2_rgbw_exact when colorimetric not in lib") {
-    // The library may have been built with or without FASTLED_RGBW_COLORIMETRIC.
-    // When without: stub falls back to rgb_2_rgbw_exact and the output is
-    // byte-for-byte identical. When with: real path runs and may differ.
-    // Test the stub path semantics: select kRGBWColorimetric, verify the
-    // output is at least sensible (not garbage, all channels in [0, 255]).
     u8 r_out, g_out, b_out, w_out;
     rgb_2_rgbw(RGBW_MODE::kRGBWColorimetric, kRGBWDefaultColorTemp,
                200, 100, 50, 255, 255, 255,
                &r_out, &g_out, &b_out, &w_out);
-    // Smoke test: no UB, output bytes are valid. Either:
-    //   stub path -> equals rgb_2_rgbw_exact: (R-min, G-min, B-min, min)
-    //              = (200-50, 100-50, 50-50, 50) = (150, 50, 0, 50)
-    //   real path -> some chromaticity-accurate tuple, all in [0, 255].
+    
+    // All outputs must be valid bytes
     FL_CHECK(r_out <= 255);
     FL_CHECK(g_out <= 255);
     FL_CHECK(b_out <= 255);
     FL_CHECK(w_out <= 255);
+    
+    // When FASTLED_RGBW_COLORIMETRIC is undefined in the library build,
+    // verify fallback to rgb_2_rgbw_exact produces identical results.
+    u8 r_exact, g_exact, b_exact, w_exact;
+    rgb_2_rgbw(RGBW_MODE::kRGBWExact, kRGBWDefaultColorTemp,
+               200, 100, 50, 255, 255, 255,
+               &r_exact, &g_exact, &b_exact, &w_exact);
+    
+#ifndef FASTLED_RGBW_COLORIMETRIC
+    // Stub fallback: should match exact mode byte-for-byte
+    FL_CHECK(r_out == r_exact);
+    FL_CHECK(g_out == g_exact);
+    FL_CHECK(b_out == b_exact);
+    FL_CHECK(w_out == w_exact);
+#endif
 }
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
FL_TEST_CASE("public API stub fallback matches rgb_2_rgbw_exact when colorimetric not in lib") {
// The library may have been built with or without FASTLED_RGBW_COLORIMETRIC.
// When without: stub falls back to rgb_2_rgbw_exact and the output is
// byte-for-byte identical. When with: real path runs and may differ.
// Test the stub path semantics: select kRGBWColorimetric, verify the
// output is at least sensible (not garbage, all channels in [0, 255]).
u8 r_out, g_out, b_out, w_out;
rgb_2_rgbw(RGBW_MODE::kRGBWColorimetric, kRGBWDefaultColorTemp,
200, 100, 50, 255, 255, 255,
&r_out, &g_out, &b_out, &w_out);
// Smoke test: no UB, output bytes are valid. Either:
// stub path -> equals rgb_2_rgbw_exact: (R-min, G-min, B-min, min)
// = (200-50, 100-50, 50-50, 50) = (150, 50, 0, 50)
// real path -> some chromaticity-accurate tuple, all in [0, 255].
FL_CHECK(r_out <= 255);
FL_CHECK(g_out <= 255);
FL_CHECK(b_out <= 255);
FL_CHECK(w_out <= 255);
}
FL_TEST_CASE("public API stub fallback matches rgb_2_rgbw_exact when colorimetric not in lib") {
u8 r_out, g_out, b_out, w_out;
rgb_2_rgbw(RGBW_MODE::kRGBWColorimetric, kRGBWDefaultColorTemp,
200, 100, 50, 255, 255, 255,
&r_out, &g_out, &b_out, &w_out);
// All outputs must be valid bytes
FL_CHECK(r_out <= 255);
FL_CHECK(g_out <= 255);
FL_CHECK(b_out <= 255);
FL_CHECK(w_out <= 255);
// When FASTLED_RGBW_COLORIMETRIC is undefined in the library build,
// verify fallback to rgb_2_rgbw_exact produces identical results.
u8 r_exact, g_exact, b_exact, w_exact;
rgb_2_rgbw(RGBW_MODE::kRGBWExact, kRGBWDefaultColorTemp,
200, 100, 50, 255, 255, 255,
&r_exact, &g_exact, &b_exact, &w_exact);
`#ifndef` FASTLED_RGBW_COLORIMETRIC
// Stub fallback: should match exact mode byte-for-byte
FL_CHECK(r_out == r_exact);
FL_CHECK(g_out == g_exact);
FL_CHECK(b_out == b_exact);
FL_CHECK(w_out == w_exact);
`#endif`
}
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@tests/fl/gfx/rgbw_colorimetric.cpp` around lines 251 - 269, The test's
name/comments promise that the stub fallback equals rgb_2_rgbw_exact but the
assertions only check byte ranges; update the FL_TEST_CASE so it calls
rgb_2_rgbw and rgb_2_rgbw_exact with the same inputs (use
RGBW_MODE::kRGBWColorimetric, kRGBWDefaultColorTemp and the same RGB/min values
used) and then: if the two outputs match exactly assert equality
(r_out,g_out,b_out,w_out == r_exact,g_exact,b_exact,w_exact), otherwise fall
back to asserting each byte is in [0,255]; keep references to the existing
function names rgb_2_rgbw and rgb_2_rgbw_exact and the test case symbol
FL_TEST_CASE (or alternatively rename the test to reflect "returns valid bytes"
if you prefer the simpler change).

@zackees
zackees force-pushed the feat/rgbw-colorimetric branch from b1d4a5e to e202c5c Compare May 30, 2026 01:06
@zackees zackees changed the title feat(rgbw): colorimetric RGB->RGBW solvers (Phase 1 of #2545) feat(rgbw): colorimetric solvers + LUT + CCT + RGBCCT (full #2545) May 30, 2026

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 2

♻️ Duplicate comments (1)
tests/fl/gfx/rgbw_colorimetric.cpp (1)

252-270: ⚠️ Potential issue | 🟡 Minor | ⚡ Quick win

Strengthen this fallback test: current assertions do not validate the stated contract.

r_out/g_out/b_out/w_out are u8, so <= 255 checks are always true and do not prove “matches rgb_2_rgbw_exact when colorimetric is not in lib” (Line 252 name/comment contract).

Proposed minimal fix
 FL_TEST_CASE("public API stub fallback matches rgb_2_rgbw_exact when colorimetric not in lib") {
@@
     u8 r_out, g_out, b_out, w_out;
     rgb_2_rgbw(RGBW_MODE::kRGBWColorimetric, kRGBWDefaultColorTemp,
                200, 100, 50, 255, 255, 255,
                &r_out, &g_out, &b_out, &w_out);
-    // Smoke test: no UB, output bytes are valid. Either:
-    //   stub path -> equals rgb_2_rgbw_exact: (R-min, G-min, B-min, min)
-    //              = (200-50, 100-50, 50-50, 50) = (150, 50, 0, 50)
-    //   real path -> some chromaticity-accurate tuple, all in [0, 255].
-    FL_CHECK(r_out <= 255);
-    FL_CHECK(g_out <= 255);
-    FL_CHECK(b_out <= 255);
-    FL_CHECK(w_out <= 255);
+    u8 r_exact, g_exact, b_exact, w_exact;
+    rgb_2_rgbw_exact(200, 100, 50, 255, 255, 255,
+                     &r_exact, &g_exact, &b_exact, &w_exact);
+#ifndef FASTLED_RGBW_COLORIMETRIC
+    FL_CHECK(r_out == r_exact);
+    FL_CHECK(g_out == g_exact);
+    FL_CHECK(b_out == b_exact);
+    FL_CHECK(w_out == w_exact);
+#else
+    FL_CHECK(r_out <= 255);
+    FL_CHECK(g_out <= 255);
+    FL_CHECK(b_out <= 255);
+    FL_CHECK(w_out <= 255);
+#endif
 }
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@tests/fl/gfx/rgbw_colorimetric.cpp` around lines 252 - 270, The test
currently only checks u8 bounds which are always true; compute the expected
tuple by calling rgb_2_rgbw_exact with the same inputs into
exp_r/exp_g/exp_b/exp_w and then update assertions to: if
FASTLED_RGBW_COLORIMETRIC is not defined, assert r_out==exp_r && g_out==exp_g &&
b_out==exp_b && w_out==exp_w (ensuring the stub fallback matches
rgb_2_rgbw_exact); otherwise (when FASTLED_RGBW_COLORIMETRIC is defined) assert
the outputs are within 0..255 to keep the smoke test. Use the existing symbols
rgb_2_rgbw, rgb_2_rgbw_exact, RGBW_MODE::kRGBWColorimetric and the
r_out/g_out/b_out/w_out variables to locate and implement this logic.
🧹 Nitpick comments (1)
src/fl/gfx/rgbw_colorimetric.h (1)

434-463: 💤 Low value

Consider caching ProfileCaches to avoid per-call matrix inversions.

solve_rgbcct rebuilds two ProfileCache instances on every call, requiring 8 matrix inversions per invocation. For per-pixel use, this is expensive. Since this is a Phase 3 helper, caching can be deferred, but worth noting for future optimization.

🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@src/fl/gfx/rgbw_colorimetric.h` around lines 434 - 463, solve_rgbcct
currently constructs two ProfileCache instances and calls build_profile_cache
for profile.warm_path and profile.cool_path on every invocation (causing
repeated matrix inversions); change the design to reuse/precompute caches
instead—either add an overload or new API that accepts prebuilt ProfileCache
objects (e.g., solve_rgbcct(const RgbcctProfile&, const ProfileCache&
warm_cache, const ProfileCache& cool_cache, ...)) or implement a shared cache
keyed by the profile identity/hash so build_profile_cache is only called when
the profile changes; update call sites to pass cached ProfileCache instances or
to populate the shared cache before per-pixel calls, keeping function behavior
of solve_rgbcct, and reference the symbols solve_rgbcct, ProfileCache,
build_profile_cache, profile.warm_path, and profile.cool_path when making
changes.
🤖 Prompt for all review comments with AI agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

Inline comments:
In `@src/fl/gfx/rgbw.cpp.hpp`:
- Around line 247-256: The allocation using new i16[...] in rgbw.cpp.hpp can
throw std::bad_alloc; replace it with a non-throwing allocation using
new(std::nothrow) and check the returned pointer (s.table.cells) for nullptr
before proceeding; if allocation fails, restore/keep s.table.N consistent and
return or propagate an error/optional rather than continuing to call
colorimetric_detail::build_lut or set s.built_for / s.built_cct; also add
`#include` <new> to enable std::nothrow.

In `@tests/fl/gfx/rgbw_colorimetric.cpp`:
- Around line 342-345: Replace the raw new[] for lut.cells with an RAII holder:
allocate a std::unique_ptr<i16[]> (or fl::unique_ptr<i16[]>) named e.g.
cells_ptr, set lut.cells = cells_ptr.get(), call build_lut(cache, &lut) while
cells_ptr remains in scope, and remove any raw delete[]; do the same for the
other occurrence around line 398 — reference: LutTable, lut.cells, build_lut.

---

Duplicate comments:
In `@tests/fl/gfx/rgbw_colorimetric.cpp`:
- Around line 252-270: The test currently only checks u8 bounds which are always
true; compute the expected tuple by calling rgb_2_rgbw_exact with the same
inputs into exp_r/exp_g/exp_b/exp_w and then update assertions to: if
FASTLED_RGBW_COLORIMETRIC is not defined, assert r_out==exp_r && g_out==exp_g &&
b_out==exp_b && w_out==exp_w (ensuring the stub fallback matches
rgb_2_rgbw_exact); otherwise (when FASTLED_RGBW_COLORIMETRIC is defined) assert
the outputs are within 0..255 to keep the smoke test. Use the existing symbols
rgb_2_rgbw, rgb_2_rgbw_exact, RGBW_MODE::kRGBWColorimetric and the
r_out/g_out/b_out/w_out variables to locate and implement this logic.

---

Nitpick comments:
In `@src/fl/gfx/rgbw_colorimetric.h`:
- Around line 434-463: solve_rgbcct currently constructs two ProfileCache
instances and calls build_profile_cache for profile.warm_path and
profile.cool_path on every invocation (causing repeated matrix inversions);
change the design to reuse/precompute caches instead—either add an overload or
new API that accepts prebuilt ProfileCache objects (e.g., solve_rgbcct(const
RgbcctProfile&, const ProfileCache& warm_cache, const ProfileCache& cool_cache,
...)) or implement a shared cache keyed by the profile identity/hash so
build_profile_cache is only called when the profile changes; update call sites
to pass cached ProfileCache instances or to populate the shared cache before
per-pixel calls, keeping function behavior of solve_rgbcct, and reference the
symbols solve_rgbcct, ProfileCache, build_profile_cache, profile.warm_path, and
profile.cool_path when making changes.
🪄 Autofix (Beta)

Fix all unresolved CodeRabbit comments on this PR:

  • Push a commit to this branch (recommended)
  • Create a new PR with the fixes

ℹ️ Review info
⚙️ Run configuration

Configuration used: Path: .coderabbit.yaml

Review profile: CHILL

Plan: Pro

Run ID: 2524f270-63ae-4b34-9ab3-01bc4016dafd

📥 Commits

Reviewing files that changed from the base of the PR and between b1d4a5e and e202c5c.

📒 Files selected for processing (5)
  • src/fl/gfx/rgbw.cpp.hpp
  • src/fl/gfx/rgbw.h
  • src/fl/gfx/rgbw_colorimetric.h
  • src/rgbw.h
  • tests/fl/gfx/rgbw_colorimetric.cpp
✅ Files skipped from review due to trivial changes (1)
  • src/rgbw.h

Comment thread src/fl/gfx/rgbw.cpp.hpp Outdated
Comment on lines +247 to +256
if (s.table.cells != nullptr) {
delete[] s.table.cells;
s.table.cells = nullptr;
}
s.table.N = s.requested_grid_n;
s.table.cells = new i16[s.requested_grid_n * s.requested_grid_n * 4];
colorimetric_detail::build_lut(get_cache(cct), &s.table);
s.built_for = active;
s.built_cct = override_cct;
}

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

⚠️ Potential issue | 🟠 Major | ⚡ Quick win

Use non-throwing allocation to avoid exception on memory failure.

new i16[...] will throw std::bad_alloc on allocation failure, violating the no-exceptions guideline. Use new(std::nothrow) and check for nullptr to return gracefully.

🛡️ Proposed fix
     if (s.table.cells != nullptr) {
         delete[] s.table.cells;
         s.table.cells = nullptr;
     }
     s.table.N = s.requested_grid_n;
-    s.table.cells = new i16[s.requested_grid_n * s.requested_grid_n * 4];
+    s.table.cells = new(std::nothrow) i16[s.requested_grid_n * s.requested_grid_n * 4];
+    if (s.table.cells == nullptr) {
+        s.enabled = false;
+        s.table.N = 0;
+        return;  // Allocation failed; disable LUT silently
+    }
     colorimetric_detail::build_lut(get_cache(cct), &s.table);

You may also need #include <new> for std::nothrow.

As per coding guidelines: "DO NOT use try-catch blocks or C++ exception handling - use error codes or fl::optional instead".

📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
if (s.table.cells != nullptr) {
delete[] s.table.cells;
s.table.cells = nullptr;
}
s.table.N = s.requested_grid_n;
s.table.cells = new i16[s.requested_grid_n * s.requested_grid_n * 4];
colorimetric_detail::build_lut(get_cache(cct), &s.table);
s.built_for = active;
s.built_cct = override_cct;
}
if (s.table.cells != nullptr) {
delete[] s.table.cells;
s.table.cells = nullptr;
}
s.table.N = s.requested_grid_n;
s.table.cells = new(std::nothrow) i16[s.requested_grid_n * s.requested_grid_n * 4];
if (s.table.cells == nullptr) {
s.enabled = false;
s.table.N = 0;
return; // Allocation failed; disable LUT silently
}
colorimetric_detail::build_lut(get_cache(cct), &s.table);
s.built_for = active;
s.built_cct = override_cct;
}
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@src/fl/gfx/rgbw.cpp.hpp` around lines 247 - 256, The allocation using new
i16[...] in rgbw.cpp.hpp can throw std::bad_alloc; replace it with a
non-throwing allocation using new(std::nothrow) and check the returned pointer
(s.table.cells) for nullptr before proceeding; if allocation fails, restore/keep
s.table.N consistent and return or propagate an error/optional rather than
continuing to call colorimetric_detail::build_lut or set s.built_for /
s.built_cct; also add `#include` <new> to enable std::nothrow.

Comment thread tests/fl/gfx/rgbw_colorimetric.cpp Resolved
@zackees
zackees force-pushed the feat/rgbw-colorimetric branch 2 times, most recently from e7f050c to a0d0ed7 Compare May 30, 2026 01:29
Implements all phases from issue #2545 in one PR:

PHASE 1 — runtime colorimetric solvers
=======================================
Two new RGBW_MODE variants gated behind FASTLED_RGBW_COLORIMETRIC:

  - kRGBWColorimetric: strict sub-gamut solver (gist sec 5). Routes target
    chromaticity to one of {RGW, RBW, BGW} and solves the 3x3 system.
    Color-accurate; uses fewer than all 4 channels per pixel.

  - kRGBWColorimetricBoosted: wx_lp_legacy white-overdrive (gist sec 9).
    Closed-form scalar LP that maximizes W subject to RGB residual >= 0.
    Same color accuracy as strict, brighter for in-gamut targets.

When FASTLED_RGBW_COLORIMETRIC is undefined (default), selecting either
mode dispatches to a stub that emits FL_WARN_ONCE and falls back to
rgb_2_rgbw_exact. FASTLED_SUPPRESS_COLORIMETRIC_FALLBACK_WARNING silences
the warn-once.

DiodeProfile struct + global setter let users supply per-strip measured xy
and luminance. Default profile (kRgbwDefaultProfile) ships as SK6812
RGBW3535 @ 6000K. kRGBWUserFunction is documented as required-last in the
enum (the dispatch table relies on it being the max value).

PHASE 2a — CCT -> W vertex (Rgbw::white_color_temp finally does something)
=========================================================================
DiodeProfile gains a nominal_cct field. When the dispatch is called with a
w_color_temperature that differs from the profile's nominal CCT, the W
vertex chromaticity is shifted via Krystek's blackbody approximation
(cct_to_xy, valid 1500K - 15000K). Cache is keyed on (profile, cct) so the
shift is precomputed once.

PHASE 2b — 2D + 1D factored LUT (FASTLED_RGBW_COLORIMETRIC_LUT)
================================================================
Optional LUT path gated behind a second compile flag. Lookup =
bilinear-interpolated xy grid (4 channels per cell, int16 quantized at 4096)
times Y_t; rebuilt automatically when the active profile or CCT changes.
Enable at runtime via enable_rgbw_colorimetric_lut(grid_n); typical
grid_n = 32 -> ~8 KB. Public API is link-safe even when the flag is off
(returns false).

PHASE 3 — RGBCCT 5-channel helper
==================================
RgbcctProfile (two DiodeProfiles: warm + cool W) and solve_rgbcct() in
fl/gfx/rgbw_colorimetric.h provide the layered-simplex math for RGBWW /
RGBCCT strips per gist sec 11-12: solve target against each W diode
separately, then line-blend the resulting RGBW tuples by an eta in [0, 1].
rgbcct_eta_for_cct() derives eta from a target CCT vs the warm/cool
reference CCTs.

Stays a helper rather than a new RGBW_MODE because the existing dispatch
signature returns 4 channels; multi-channel public dispatch is left for
when there is a concrete 5-channel chipset wired through the rest of
FastLED's pipeline.

DESIGN
======
Per-pixel solver math (xyY <-> XYZ, 3x3 invert, 3x3 matvec, barycentric
containment, strict sub-gamut solve, wx_lp solve, LUT lookup, RGBCCT
blend) lives as inline functions in fl/gfx/rgbw_colorimetric.h so tests
can validate the algorithms directly regardless of how the library was
built. The library-side dispatch in rgbw.cpp.hpp owns the lazy
Singleton<ColorimetricCacheHolder> and Singleton<LutStateHolder> state.

TESTS
=====
fl_gfx_rgbw_colorimetric (new): 17 test cases covering xyY/XYZ round-trip,
3x3 invert correctness, barycentric inside/outside, strict subgamut on
pure primaries / black / in-gamut chromaticity preservation, wx_lp boost
behavior, Krystek vs published Planckian-locus values at 2700/4000/6500K,
CCT-driven W-vertex shift, LUT accuracy vs closed-form on a chromaticity
sweep (max xy error < 0.01 at N=32), public-API stub fallback, public-API
LUT enable/disable link safety, RGBCCT chromaticity preservation across
the warm<->cool blend, rgbcct_eta_for_cct linear interp.

Co-Authored-By: Claude Opus 4.7 <[email protected]>
@zackees
zackees force-pushed the feat/rgbw-colorimetric branch from a0d0ed7 to 5b1cac5 Compare May 30, 2026 01:33

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 3

🤖 Prompt for all review comments with AI agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

Inline comments:
In `@src/fl/gfx/rgbw_colorimetric.cpp.hpp`:
- Around line 22-26: When cct_override is applied you must persist the effective
white chromaticity so the barycentric/simplex selection and the matrix solve use
the same white; after computing xy_w (via cct_to_xy) assign the effective values
back into the cache/profile white so subsequent code uses them (e.g. update
cache->profile->xy_w or otherwise replace usages of p->xy_w with the computed
xy_w) and then call xyY_to_XYZ to rebuild cache->P_W; apply the same change in
the other two affected blocks (the ones around lines 71-78 and 123-128) so all
solvers see the overridden white.
- Around line 184-187: The LUT creation and lookup are not hardened against
grid_n < 2 and empty cells: modify build_lut so it first validates grid_n >= 2
and returns an “empty” LutTable (set lut.N = 0 and lut.cells = nullptr or
equivalent) when invalid, and otherwise compute the allocation size using an
unsigned size_t product (size_t total = static_cast<size_t>(grid_n) * grid_n *
4), check for overflow/zero before allocating, then set lut.N = grid_n and
allocate lut.cells with that size; additionally, update lookup_lut to
early-return or handle cases where lut.N < 2 or lut.cells is null to avoid
1/(N-1) division and out-of-bounds reads (reference symbols: build_lut,
lookup_lut, LutTable, lut.N, lut.cells).

In `@src/fl/gfx/rgbw_colorimetric.h`:
- Around line 28-109: Many inline helpers and public solver signatures still use
fixed-size C arrays; update parameter types to fl::span to avoid baked sizes:
convert cct_to_xy(float out[2]) → cct_to_xy(fl::span<float> out) and
xyY_to_XYZ(float out[3]) → xyY_to_XYZ(fl::span<float> out), invert3x3(const
float in[3][3], float out[3][3]) → invert3x3(fl::span<const float> in,
fl::span<float> out) (use a 3x3 linearized span or span of 3 spans as your
convention), matvec3(const float M[3][3], const float v[3], float out[3]) →
matvec3(fl::span<const float> M, fl::span<const float> v, fl::span<float> out),
barycentric_xy(const float t[2], const float A[2], const float B[2], const float
C[2], float bary[3]) → barycentric_xy(fl::span<const float> t, fl::span<const
float> A, fl::span<const float> B, fl::span<const float> C, fl::span<float>
bary), and update the public solver declarations that use out_rgbw, xy_t, out
etc. to use fl::span<const float> / fl::span<float>; adjust callers to pass
spans (or pointer+size wrappers) and keep semantics (size checks/asserts) inside
each function.
🪄 Autofix (Beta)

Fix all unresolved CodeRabbit comments on this PR:

  • Push a commit to this branch (recommended)
  • Create a new PR with the fixes

ℹ️ Review info
⚙️ Run configuration

Configuration used: Path: .coderabbit.yaml

Review profile: CHILL

Plan: Pro

Run ID: ad7730d2-791f-497a-bf95-cf0702f01d4a

📥 Commits

Reviewing files that changed from the base of the PR and between e7f050c and a0d0ed7.

📒 Files selected for processing (6)
  • src/fl/gfx/rgbw.cpp.hpp
  • src/fl/gfx/rgbw.h
  • src/fl/gfx/rgbw_colorimetric.cpp.hpp
  • src/fl/gfx/rgbw_colorimetric.h
  • src/rgbw.h
  • tests/fl/gfx/rgbw_colorimetric.cpp
🚧 Files skipped from review as they are similar to previous changes (4)
  • src/rgbw.h
  • src/fl/gfx/rgbw.cpp.hpp
  • src/fl/gfx/rgbw.h
  • tests/fl/gfx/rgbw_colorimetric.cpp

Comment on lines +22 to +26
float xy_w[2] = { p->xy_w[0], p->xy_w[1] };
if (cct_override >= 1500 && cct_override <= 15000) {
cct_to_xy(cct_override, xy_w);
}
xyY_to_XYZ(xy_w[0], xy_w[1], p->lum_w, cache->P_W);

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

⚠️ Potential issue | 🟠 Major | ⚡ Quick win

Persist the effective W chromaticity in the cache.

When cct_override is applied, cache->P_W is rebuilt from the shifted white point, but both strict solvers still do their barycentric routing against cache.profile->xy_w. That means the simplex selection is based on the original white vertex while the matrix solve uses the overridden one, so warm/cool caches can reject valid targets or choose the wrong sub-gamut.

Suggested fix
 struct ProfileCache {
     const DiodeProfile* profile;
+    float xy_w[2];
     float P_R[3], P_G[3], P_B[3], P_W[3];
     float P_RGB_inv[3][3];
     float P_RGW_inv[3][3];
@@
     float xy_w[2] = { p->xy_w[0], p->xy_w[1] };
     if (cct_override >= 1500 && cct_override <= 15000) {
         cct_to_xy(cct_override, xy_w);
     }
+    cache->xy_w[0] = xy_w[0];
+    cache->xy_w[1] = xy_w[1];
     xyY_to_XYZ(xy_w[0], xy_w[1], p->lum_w, cache->P_W);
@@
-        { cache.profile->xy_r, cache.profile->xy_g, cache.profile->xy_w,
+        { cache.profile->xy_r, cache.profile->xy_g, cache.xy_w,
           cache.P_RGW_inv, 0, 1, 3 },
-        { cache.profile->xy_r, cache.profile->xy_b, cache.profile->xy_w,
+        { cache.profile->xy_r, cache.profile->xy_b, cache.xy_w,
           cache.P_RBW_inv, 0, 2, 3 },
-        { cache.profile->xy_b, cache.profile->xy_g, cache.profile->xy_w,
+        { cache.profile->xy_b, cache.profile->xy_g, cache.xy_w,
           cache.P_BGW_inv, 2, 1, 3 },

Also applies to: 71-78, 123-128

🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@src/fl/gfx/rgbw_colorimetric.cpp.hpp` around lines 22 - 26, When cct_override
is applied you must persist the effective white chromaticity so the
barycentric/simplex selection and the matrix solve use the same white; after
computing xy_w (via cct_to_xy) assign the effective values back into the
cache/profile white so subsequent code uses them (e.g. update
cache->profile->xy_w or otherwise replace usages of p->xy_w with the computed
xy_w) and then call xyY_to_XYZ to rebuild cache->P_W; apply the same change in
the other two affected blocks (the ones around lines 71-78 and 123-128) so all
solvers see the overridden white.

Comment on lines +184 to +187
LutTable build_lut(const ProfileCache& cache, int grid_n) FL_NOEXCEPT {
LutTable lut;
lut.N = grid_n;
lut.cells = fl::make_unique<i16[]>(static_cast<fl::size_t>(grid_n * grid_n * 4));

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

⚠️ Potential issue | 🟠 Major | ⚡ Quick win

Harden the LUT path against invalid dimensions and empty tables.

build_lut() accepts grid_n <= 1, then immediately computes 1.0f / (N - 1) and allocates with grid_n * grid_n * 4 in signed int. lookup_lut() also assumes lut.N >= 2 and cells is populated. A bad input here turns into divide-by-zero, bogus allocation sizes, or OOB reads.

Suggested fix
 LutTable build_lut(const ProfileCache& cache, int grid_n) FL_NOEXCEPT {
     LutTable lut;
+    if (grid_n < 2) {
+        return lut;
+    }
-    lut.N = grid_n;
-    lut.cells = fl::make_unique<i16[]>(static_cast<fl::size_t>(grid_n * grid_n * 4));
+    const fl::size_t n = static_cast<fl::size_t>(grid_n);
+    lut.N = grid_n;
+    lut.cells = fl::make_unique<i16[]>(n * n * 4u);
@@
 void lookup_lut(const LutTable& lut, const float xy_t[2], float Y_t,
                 float out_rgbw[4]) FL_NOEXCEPT {
+    out_rgbw[0] = out_rgbw[1] = out_rgbw[2] = out_rgbw[3] = 0.0f;
+    if (lut.N < 2 || !lut.cells.get()) {
+        return;
+    }
     const int N = lut.N;
     const float dx = lut.xy_max[0] - lut.xy_min[0];
     const float dy = lut.xy_max[1] - lut.xy_min[1];
+    if (dx <= 0.0f || dy <= 0.0f) {
+        return;
+    }

Also applies to: 203-205, 225-243

🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@src/fl/gfx/rgbw_colorimetric.cpp.hpp` around lines 184 - 187, The LUT
creation and lookup are not hardened against grid_n < 2 and empty cells: modify
build_lut so it first validates grid_n >= 2 and returns an “empty” LutTable (set
lut.N = 0 and lut.cells = nullptr or equivalent) when invalid, and otherwise
compute the allocation size using an unsigned size_t product (size_t total =
static_cast<size_t>(grid_n) * grid_n * 4), check for overflow/zero before
allocating, then set lut.N = grid_n and allocate lut.cells with that size;
additionally, update lookup_lut to early-return or handle cases where lut.N < 2
or lut.cells is null to avoid 1/(N-1) division and out-of-bounds reads
(reference symbols: build_lut, lookup_lut, LutTable, lut.N, lut.cells).

Comment on lines +28 to +109
inline void cct_to_xy(int cct, float out[2]) FL_NOEXCEPT {
const float T = static_cast<float>(
(cct < 1500) ? 1500 : ((cct > 15000) ? 15000 : cct));
const float T2 = T * T;
const float u_num = 0.860117757f + 1.54118254e-4f * T + 1.28641212e-7f * T2;
const float u_den = 1.0f + 8.42420235e-4f * T + 7.08145163e-7f * T2;
const float v_num = 0.317398726f + 4.22806245e-5f * T + 4.20481691e-8f * T2;
const float v_den = 1.0f - 2.89741816e-5f * T + 1.61456053e-7f * T2;
const float u = u_num / u_den;
const float v = v_num / v_den;
const float den = 2.0f * u - 8.0f * v + 4.0f;
out[0] = 3.0f * u / den;
out[1] = 2.0f * v / den;
}

inline void xyY_to_XYZ(float x, float y, float Y, float out[3]) FL_NOEXCEPT {
if (y < 1e-12f) {
out[0] = out[1] = out[2] = 0.0f;
return;
}
const float inv_y = 1.0f / y;
out[0] = x * Y * inv_y;
out[1] = Y;
out[2] = (1.0f - x - y) * Y * inv_y;
}

inline bool invert3x3(const float in[3][3], float out[3][3]) FL_NOEXCEPT {
const float a = in[0][0], b = in[0][1], c = in[0][2];
const float d = in[1][0], e = in[1][1], f = in[1][2];
const float g = in[2][0], h = in[2][1], i = in[2][2];
const float det = a * (e * i - f * h) - b * (d * i - f * g) + c * (d * h - e * g);
if (fl::fabs(det) < 1e-20f) {
return false;
}
const float inv_det = 1.0f / det;
out[0][0] = (e * i - f * h) * inv_det;
out[0][1] = (c * h - b * i) * inv_det;
out[0][2] = (b * f - c * e) * inv_det;
out[1][0] = (f * g - d * i) * inv_det;
out[1][1] = (a * i - c * g) * inv_det;
out[1][2] = (c * d - a * f) * inv_det;
out[2][0] = (d * h - e * g) * inv_det;
out[2][1] = (b * g - a * h) * inv_det;
out[2][2] = (a * e - b * d) * inv_det;
return true;
}

inline void matvec3(const float M[3][3], const float v[3], float out[3]) FL_NOEXCEPT {
out[0] = M[0][0] * v[0] + M[0][1] * v[1] + M[0][2] * v[2];
out[1] = M[1][0] * v[0] + M[1][1] * v[1] + M[1][2] * v[2];
out[2] = M[2][0] * v[0] + M[2][1] * v[1] + M[2][2] * v[2];
}

inline bool barycentric_xy(const float t[2], const float A[2], const float B[2],
const float C[2], float bary[3]) FL_NOEXCEPT {
const float v0x = B[0] - A[0], v0y = B[1] - A[1];
const float v1x = C[0] - A[0], v1y = C[1] - A[1];
const float v2x = t[0] - A[0], v2y = t[1] - A[1];
const float d00 = v0x * v0x + v0y * v0y;
const float d01 = v0x * v1x + v0y * v1y;
const float d11 = v1x * v1x + v1y * v1y;
const float d20 = v2x * v0x + v2y * v0y;
const float d21 = v2x * v1x + v2y * v1y;
const float den = d00 * d11 - d01 * d01;
if (fl::fabs(den) < 1e-20f) {
return false;
}
const float inv_den = 1.0f / den;
const float u = (d11 * d20 - d01 * d21) * inv_den;
const float v = (d00 * d21 - d01 * d20) * inv_den;
bary[0] = 1.0f - u - v;
bary[1] = u;
bary[2] = v;
return true;
}

inline u8 quantize_u8(float v) FL_NOEXCEPT {
const float scaled = v * 255.0f + 0.5f;
if (scaled <= 0.0f) return 0;
if (scaled >= 255.0f) return 255;
return static_cast<u8>(scaled);
}

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🛠️ Refactor suggestion | 🟠 Major | 🏗️ Heavy lift

🧩 Analysis chain

🏁 Script executed:

#!/bin/bash
set -euo pipefail

# Locate the target file (fail fast if missing)
ls -la src/fl/gfx/rgbw_colorimetric.h

# Show the relevant line ranges with numbers
sed -n '1,220p' src/fl/gfx/rgbw_colorimetric.h | nl -ba | sed -n '1,220p'

# Focus on occurrences of raw array parameters in function signatures
rg -n --no-heading "(\w+\s*\[\s*\d*\s*\])|(\w+\s*\[\s*\])" src/fl/gfx/rgbw_colorimetric.h

# Specifically extract the blocks around the mentioned helper signatures
sed -n '1,140p' src/fl/gfx/rgbw_colorimetric.h | nl -ba
sed -n '140,240p' src/fl/gfx/rgbw_colorimetric.h | nl -ba

Repository: FastLED/FastLED

Length of output: 200


🏁 Script executed:

#!/bin/bash
set -euo pipefail

FILE="src/fl/gfx/rgbw_colorimetric.h"

# Print file first 240 lines with line numbers (via awk) but trimmed to keep output reasonable
awk '{printf "%5d\t%s\n", NR, $0}' "$FILE" | sed -n '1,240p'

# Find raw-array-looking parameters in the whole file
rg -n --no-heading --context 2 "(\w+\s*\[\s*\d*\s*\])|(\w+\s*\[\s*\])" "$FILE" || true

# Also show lines specifically around the originally referenced regions
awk '{printf "%5d\t%s\n", NR, $0}' "$FILE" | sed -n '20,130p'
awk '{printf "%5d\t%s\n", NR, $0}' "$FILE" | sed -n '150,230p'

Repository: FastLED/FastLED

Length of output: 23927


Replace raw array parameters with fl::span in src/fl/gfx/rgbw_colorimetric.h.

  • Inline helpers (lines ~28-109) use raw array parameters like float out[2], float out[3], const float in[3][3], float out[3][3], const float t[2]/const float A[2]/float bary[3].
  • Public solver declarations (lines ~169-207) expose raw arrays like float out_rgbw[4], const float xy_t[2], and float out[5].

Switch these to fl::span<const float> / fl::span<float> to follow the header API guideline and avoid baking size-erasing raw arrays into the new surface.

🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@src/fl/gfx/rgbw_colorimetric.h` around lines 28 - 109, Many inline helpers
and public solver signatures still use fixed-size C arrays; update parameter
types to fl::span to avoid baked sizes: convert cct_to_xy(float out[2]) →
cct_to_xy(fl::span<float> out) and xyY_to_XYZ(float out[3]) →
xyY_to_XYZ(fl::span<float> out), invert3x3(const float in[3][3], float
out[3][3]) → invert3x3(fl::span<const float> in, fl::span<float> out) (use a 3x3
linearized span or span of 3 spans as your convention), matvec3(const float
M[3][3], const float v[3], float out[3]) → matvec3(fl::span<const float> M,
fl::span<const float> v, fl::span<float> out), barycentric_xy(const float t[2],
const float A[2], const float B[2], const float C[2], float bary[3]) →
barycentric_xy(fl::span<const float> t, fl::span<const float> A, fl::span<const
float> B, fl::span<const float> C, fl::span<float> bary), and update the public
solver declarations that use out_rgbw, xy_t, out etc. to use fl::span<const
float> / fl::span<float>; adjust callers to pass spans (or pointer+size
wrappers) and keep semantics (size checks/asserts) inside each function.

@zackees
zackees merged commit d686427 into master May 30, 2026
10 checks passed
zackees added a commit that referenced this pull request May 30, 2026
…lock (#2589)

Two CodeRabbit follow-ups for src/fl/gfx/rgbw_colorimetric.cpp.hpp:

- B1: build_profile_cache warned on invert3x3 failure but still wrote
  garbage matrices into cache->P_*_inv. Downstream matvec3() then
  produced undefined output. Zero-init each failed matrix so output is
  deterministic (zero) on degenerate profiles.

- B7: lines 43-46 and 51-54 were near-identical comment blocks about
  degenerate primaries. Removed the second block.

Addresses CodeRabbit findings B1 (originally #2552) and B7 (#2554) per
meta #2580.
@zackees
zackees deleted the feat/rgbw-colorimetric branch May 30, 2026 20:02
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.

1 participant