Skip to content

fix(rgbw_colorimetric) Fix dual-channel Y ratio solving, Fix 3-channel solve granularity issues, re-implement legacy_lp solver - #2752

Merged
zackees merged 4 commits into
FastLED:masterfrom
JChalka:master
Jun 4, 2026

Conversation

@JChalka

@JChalka JChalka commented Jun 4, 2026 •

Copy link
Copy Markdown
Contributor

medium Verification session from the rgbw_colorimetric contained in this PR:
fastled_rgbw_nativegamut_d65whitepoint_subgamut_model_mediumpatchset_dualchannel_3channelfix.csv

No more illegal topology solves, no more bad-ratio dual-channel solves, 3-channel & LP_legacy solver now very closely match the math model output

Metric | Result
-- | --
Rows | 244
Pass | 159
Fail | 85
Mean dE | 2.16
Median dE | 1.24
Max dE | 10.49
Illegal strict single/dual topology | 0
Illegal LP single/dual topology | 0
strict_rgbw16 == mcu_solved_rgbw16 | 244 / 244
red_half:      old 65535/0/0/56602       -> new 32768/0/0/0
green_half:    old 0/65535/0/35169       -> new 0/32768/0/0
cyan:          old 0/24029/65535/38635   -> new 0/65535/38770/0
magenta_half:  old 19256/0/57592/58768   -> new 32768/0/10310/0
yellow_half:   old mostly maxed behavior -> new 32768/17427/0/0

current dE failures are mostly a symptom of the actual capture test bench : Measured primaries are wall-captured primaries, not direct diode. Colorimeter/FastLED/Model is collecting/using those wall-reflected xy coordinates for solves which is really "LED primary blended into wall color, not direct-diode measured xy coordinates" so some error, especially at low Y, is expected.

This PR does not focus on being entirely performant, although the math model & FastLED analytical model are now aligned as of this PR. Checks should be made to make sure that things are still hitting performance targets. I have not tested the modified max-white LP endpoint solver within this verification run, just sub-gamut & legacy_lp that was re-implemented. The good news is that the legacy_LP solver now very closely matches the math model implementation

Summary by CodeRabbit

  • Bug Fixes

    • Improved color accuracy, white-balance and out-of-gamut handling for edge and extreme rendering cases.
  • New Features

    • Added a chromaticity-preserving endpoint projection option for tighter, predictable gamut mapping and balanced white handling.
  • Refactor

    • Reworked solver routing so native single- and dual-channel behaviors are enforced, preserving value vs. chroma for interior colors.
  • Documentation

    • Clarified solver model, topology behavior and source-matrix scaling rationale.

JChalka added 3 commits June 4, 2026 10:21
…hority & 3-channel linearity

This patch restores the reference math-model structure while preserving the analytical FastLED runtime path. It separates native single-axis identity from native dual-edge authority, solves dual edges as fixed-topology measured-XYZ solves instead of passthrough, applies chroma/value separation for strict interior solves, and restores wx_lp_legacy as a chromaticity-preserving max-feasible-W solver separate from boosted overdrive.

This PR does not aim to be entirely performant and analysis should be done to see if things could be improved to decrease actual compute time.
@coderabbitai

coderabbitai Bot commented Jun 4, 2026 •

Copy link
Copy Markdown

Review Change Stack

No actionable comments were generated in the recent review. 🎉

ℹ️ Recent review info
⚙️ Run configuration

Configuration used: Path: .coderabbit.yaml

Review profile: CHILL

Plan: Pro

Run ID: d7afa045-256b-42c7-9e77-c29a633b8294

📥 Commits

Reviewing files that changed from the base of the PR and between 2f3972b and c6d7774.

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

📝 Walkthrough

Walkthrough

Refactors the RGBW colorimetric solver: profile-aware source-space M_src scaling, new numeric/solver primitives for strict hull routing, native-topology fast-paths for 1–2 emitters, a bounded LP-style wx_lp_legacy solver, and adjustments to wx_overdrive RGBW construction.

Changes

RGBW Colorimetric Solver Refactoring

Layer / File(s) Summary
Implementation map and comments
src/fl/gfx/rgbw_colorimetric.cpp.hpp
Adds an expanded implementation map and comments describing build_profile_cache, strict routing, wx_lp_legacy, wx_overdrive, and the value/chroma separation invariant.
Source space M_src scaling in build_profile_cache
src/fl/gfx/rgbw_colorimetric.cpp.hpp
build_profile_cache() now conditionally scales cache->M_src when cache->has_source_space is true, computing a scale from source-white XYZ at Y=1 using the best-conditioned sub-gamut inverse (fallback to RGB inverse) and applying it multiplicatively to M_src.
Numeric helpers and source→XYZ conversion
src/fl/gfx/rgbw_colorimetric.cpp.hpp
Adds local numeric helpers (max3f, zero/normalize, column selection) and source_rgb_to_XYZ() that converts source RGB to absolute XYZ using cache.M_src when available, with a measured-emitter fallback.
Native/topology fixed-topology solvers
src/fl/gfx/rgbw_colorimetric.cpp.hpp
Introduces native_single_identity(), solve_fixed_topology_least_squares() (n=1/2 with non-negative fallback), and solve_native_dual_edge_fixed_topology() for edge-locked dual-emitter solves with endpoint normalization/rescaling.
Strict endpoint solve and barycentric routing
src/fl/gfx/rgbw_colorimetric.cpp.hpp
Implements solve_strict_subgamut_from_XYZ() to compute xy, project out-of-hull targets, and route into three sub-gamuts via barycentric containment using cached inverses; uses max3f and non-negative clamping before normalization.
Rewritten solve_strict_subgamut with native topology authority
src/fl/gfx/rgbw_colorimetric.cpp.hpp
solve_strict_subgamut() now enforces native topology by active-channel count: single-channel identity, dual-channel native dual-edge solver, interior three-channel solves full-chroma endpoint then rescales by original value and normalizes.
New solve_wx_lp_legacy and overdrive refinement
src/fl/gfx/rgbw_colorimetric.cpp.hpp
Adds solve_wx_balanced_fraction_for_xy() constrained search and non-static solve_wx_lp_legacy() which projects to the strict hull, solves the balanced wx fraction, and falls back to strict XYZ solver on failure; updates solve_wx_overdrive() to build full as full[0..2]=max(a - w*d,0), full[3]=w, normalize, rescale by original value, and renormalize.
Header docs and public declaration
src/fl/gfx/rgbw_colorimetric.h
Rewrites solver documentation (distinguishing wx_lp_legacy from overdrive), clarifies native-mode topology authority and activity classification, expands ProfileCache scaling rationale, and adds bool solve_wx_lp_legacy(const ProfileCache&, float, float, float, float out_rgbw[4]) FL_NOEXCEPT; declaration.

Estimated code review effort

🎯 4 (Complex) | ⏱️ ~60 minutes

Possibly related issues

Possibly related PRs

Poem

🐰 I hop through chroma, value in hand,
Mapping source white to bright land,
Edges locked, hulls aligned,
Legacy LP seeks the shine,
RGBW sings, balanced and grand.

🚥 Pre-merge checks | ✅ 4 | ❌ 1

❌ Failed checks (1 warning)

Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 60.87% 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 directly addresses the three main changes in the PR: dual-channel Y ratio solving fix, 3-channel solve granularity improvements, and legacy_lp solver re-implementation, matching the substantial refactoring described in the changeset.
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 unit tests (beta)
  • Create PR with unit tests

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: 1

🤖 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 240-246: Zero any channel <= topology epsilon before taking native
paths: update native_single_identity to test s_r, s_g, s_b against the topology
threshold used by count_active_channels() (1/65535) and set out[i]=0.0f for any
sub-threshold component before clamping/copying; likewise modify the native
dual/tri functions (and the call site in solve_native_dual_edge_fixed_topology
that passes the third channel into source_rgb_to_XYZ()) to force sub-threshold
channels to zero so the 1‑ and 2‑channel topologies cannot emit bleed or skewed
ratios (reference symbols: native_single_identity,
solve_native_dual_edge_fixed_topology, count_active_channels). Ensure the check
uses the same epsilon constant and is performed before any native-path color
conversions or outputs are computed.
🪄 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: 1cfdf376-ccfb-4eae-9f8b-077e60f02fe2

📥 Commits

Reviewing files that changed from the base of the PR and between 713edd6 and 2f3972b.

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

Comment thread src/fl/gfx/rgbw_colorimetric.cpp.hpp Resolved
@JChalka

JChalka commented Jun 4, 2026

Copy link
Copy Markdown
Contributor Author

I seem to have accidentally removed some documentation, so before this gets merged I'll attach updated files that are properly documented. FastLED is too large a project to have missing function documentation so I recognize this as "should be fixed now, not later"

add back documentation for rgbw_colorimetric
@JChalka

JChalka commented Jun 4, 2026

Copy link
Copy Markdown
Contributor Author

Just an informational follow-up as I've run a full 1885 patch set verification against the sub-gamut model (lp_legacy was not checked for dE but the output values were still compared against the 256 LP cube to see how close it is to the tetrahedral interpolated values from the LUT)

fastled_rgbw_nativegamut_d65whitepoint_subgamut_model_fullpatch.csv
native_wx_lp_legacy_linear_256cube_16bittemporalbfi.csv
native_sub_gamut_linear_256cube_16bittemporalbfi.csv

I ran a full 1,885-row native/D65/full-patch verification against this PRs analytical implementation and compared it row-by-row against the 256-cube outputs generated by the reference math models. LUT Output values are not expected to be 1:1 with the math model or FastLED implementation of the math model, as tetrahedral interpolation and no 1:1 LUT means we introduce some interpolation error when solving.

The key structural checks now pass:

Check FastLED strict FastLED LP column sub-gamut cube LP cube
Illegal single/dual topology rows 0 0 0 0
Single-axis non-identity rows 0 0 0 0

Measured dE is now in the same broad range as the cube/math-model verifier runs. These are wall-reflected bench captures, so the remaining failures are expected to include wall/backdrop spectral effects, low-Y noise, green-biased wall reflectance, and current light leak at black.

Run Pass Fail Mean dE Median dE p95 dE Max dE
FastLED strict verifier 1139 / 1884 745 2.43 1.40 8.23 24.41
sub-gamut cube verifier 1211 / 1883 672 2.13 1.63 5.75 17.67
LP legacy cube verifier 1215 / 1884 669 2.03 1.48 5.54 14.71

FastLED strict output vs the sub-gamut 256 cube:

Bucket Rows Exact ≤256 ≤1024 Mean Δmax Median Δmax p95 Δmax Max Δmax
all 1885 17 415 1346 747 610 1678 4325
single 16 16 16 16 0 0 0 0
dual 257 0 88 226 513 394 1246 1604
neutral 67 0 8 29 1165 1186 2197 2263
mixed3 1544 0 302 1074 776 659 1677 4325

FastLED LP column vs the wx_lp_legacy 256 cube, output comparison only:

Bucket Rows Exact ≤256 ≤1024 Mean Δmax Median Δmax p95 Δmax Max Δmax
all 1885 17 612 1508 605 415 1348 15775
single 16 16 16 16 0 0 0 0
dual 257 0 101 217 502 365 1291 1813
neutral 67 0 5 60 672 715 1052 1250
mixed3 1544 0 489 1214 626 423 1374 15775

Representative rows:

Patch Input RGB16 FastLED strict sub-gamut cube Strict Δmax FastLED LP LP cube LP Δmax FastLED dE
neutral_50pct 32768/32768/32768 2375/0/7985/32768 2266/0/6799/32214 1186 32768/16164/17548/32768 32513/15706/16964/32214 584 0.09
white 65535/65535/65535 4750/0/15970/65535 4289/0/13766/65535 2204 65535/32328/35095/65535 65535/31350/34115/65535 980 0.42
red 65535/0/0 65535/0/0/0 65535/0/0/0 0 65535/0/0/0 65535/0/0/0 0 0.98
green 0/65535/0 0/65535/0/0 0/65535/0/0 0 0/65535/0/0 0/65535/0/0 0 2.19
blue 0/0/65535 0/0/65535/0 0/0/65535/0 0 0/0/65535/0 0/0/65535/0 0 6.06
cyan 0/65535/65535 0/65535/38770/0 0/65458/38474/0 296 0/65535/38770/0 0/65535/38532/0 238 0.57
magenta 65535/0/65535 65535/0/20620/0 65040/0/19423/0 1197 65535/0/20620/0 65535/0/19794/0 826 0.99
yellow 65535/65535/0 65535/34854/0/0 64736/33903/0/0 951 65535/34854/0/0 65535/33794/0/0 1060 3.59
cyan_half 0/32768/32768 0/32768/19385/0 0/32754/19214/0 171 0/32768/19385/0 0/32769/19249/0 136 2.30
magenta_half 32768/0/32768 32768/0/10310/0 32450/0/9748/0 562 32768/0/10310/0 32513/0/9855/0 455 7.31
yellow_half 32768/32768/0 32768/17427/0/0 32419/16814/0/0 613 32768/17427/0/0 32513/16770/0/0 657 6.95
h315_s015_v100 65535/55705/63077 35438/0/20984/55705 34671/0/19239/55479 1745 65535/10779/31907/65535 65535/10136/30957/65535 950 0.98

One nuance: for strict/sub-gamut, some max(input RGB16) == 65535 rows do not produce a 65535 output channel. In this run, 108 of 239 full-scale-input rows had max(output RGBW16) < 65535 in strict mode, while the LP column preserved full output scale for all of those rows. The affected strict rows generally still pass, so this looks like a policy question rather than a correctness bug: preserve exact colorimetric target/value behavior, or optionally add a “max-preserve/full-scale anchor” policy that forces at least one output channel to full scale when any input channel is full scale. I would leave that as a possible follow-up rather than block this PR on it.

@zackees
zackees merged commit 2829165 into FastLED:master Jun 4, 2026
6 checks passed
@fastled-project-sync fastled-project-sync Bot moved this from Triage to Done in FastLED Tracker Jun 4, 2026
zackees added a commit that referenced this pull request Jun 4, 2026
…ted project_automation.yml (closes #2757) (#2759)

* ci: hard-block external-fork PRs from all workflow runs; ban pull_request_target (#2757)

Two related hardening changes:

1. **Hard-block fork PRs** on the 6 workflows that trigger on
   `pull_request:` — `build_esp32s3`, `build_teensy41`, `build_uno`,
   `build_wasm`, `example_test_linux`, `unit_test_linux`. Add a job-level
   `if:` guard:

       if: github.event.pull_request == null ||
           github.event.pull_request.head.repo.full_name == github.repository

   The first clause lets `push` / `workflow_dispatch` / `schedule` / etc.
   continue to run (those events have no `pull_request` context). The
   second clause matches only when the PR head repo IS the base repo
   (i.e. branch in FastLED/FastLED, never a fork).

   Behavior change: external-fork PRs now skip the entire build matrix
   silently (the jobs evaluate to `skipped`, not failed). Internal-branch
   PRs and pushes are unaffected.

2. **Ban pull_request_target** entirely. The only active user was
   `project_automation.yml`, which used it to keep a project board in
   sync with PR open/close/draft events. That trigger is removed; the
   `issues:` trigger remains. PR-driven board sync is intentionally
   dropped — the trigger has historically been the highest-risk surface
   in GitHub Actions (it runs in trusted context with secrets even on
   fork PRs) and the user explicitly banned it.

   The `build_clone_and_compile.yml` file already had `pull_request_target`
   disabled via comment — that pre-existing decision is now in line with
   repo policy.

Verification:
- `grep -rln 'pull_request_target' .github/` returns only two files, both
  showing the trigger inside a comment (one historical, one new), zero
  active uses.
- `bash lint` clean.

Filed under issue #2757 (which surfaced the cost-control concern after
external PR #2752 triggered the full CI matrix; user's follow-up
directives during review escalated to a hard block on fork PRs and a
full ban on pull_request_target).

Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>

* ci(project_automation): restore pull_request_target after audit; document safety invariants

Reverses the part of the previous commit that removed pull_request_target
from project_automation.yml. The trigger is needed for PR-side project
board sync (open / close / draft state changes) — a vanilla pull_request
trigger has no access to the App private key required to write to the
project, so pull_request_target is the only viable option.

The pull_request_target ban from the previous commit still applies to
the rest of the repo — project_automation.yml is the documented
exception.

This commit also adds a 30-line security comment block above the
trigger declaration encoding the FIVE invariants that make this
specific pull_request_target usage safe:

  1. NEVER add `ref:` to actions/checkout (must stay on base ref)
  2. NEVER run a fork-controlled script (only `python ci/github_project_sync.py`)
  3. NEVER interpolate PR-controlled data into `run:` blocks (use `env:` only)
  4. Keep `permissions:` minimal (currently `contents: read`)
  5. App token must remain project-scoped only

A second comment marker is placed directly on the actions/checkout step
warning future editors not to add `ref:`.

Audit performed 2026-06-04 under #2757. All five invariants verified
holding. The script `ci/github_project_sync.py` was also audited:
- inputs read only via `os.environ.get()`
- passed to `gh api` via `-f`/`-F` positional flags (no shell)
- GraphQL queries use `$variable` placeholders (no string concat)
- env vars contain only GitHub-controlled metadata + repo vars + App token

Net effect: identical functional behavior to pre-#2759 state on
project_automation.yml; the explicit invariant comments are
maintenance-grade documentation to prevent future regressions.

Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>

---------

Co-authored-by: Claude Opus 4.7 (1M context) <[email protected]>
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.

2 participants