Skip to content

Conversation

@sayhiben
Copy link

@sayhiben sayhiben commented Jan 21, 2026

Overview

image image image

I'm designing a fancy sign for a craft fair booth with an engraved sheet of acrylic in front. In order to properly light it, I would like to define segments for various shapes in the engraved sheet such that I can apply different effects to each area. Currently, support for this is limited to ledmaps (only one across all segments), jMaps (1D -> 2D translation only), and grouping (only works for specific designs)

This PR adds support for clipping masks per segment, defined in virtual LED space. This enables overlapping segments to render distinct effects/palettes while preserving normal segment geometry and mappings.

Summary of changes

  • Add per‑segment mask clipping via segmaskX.json files (1D + 2D).
  • Expose mask selection + invert in the UI (MM‑specific items marked with 🌜).
  • Stream‑parse mask files (ledmap‑style) and enumerate available masks.
  • Make 1D mask gating work on matrix installs and add a safety reset on failed mask loads.

How it works

  • Mask storage: bit‑packed 0/1 mask loaded from /segmaskX.json (stream parser like ledmap).
  • Mask checks:
    • 2D: mask checked in setPixelColorXY_*.
    • 1D: mask checked in setPixelColor with !is2D() so 1D segments still mask on matrix installs.
  • JSON API: segment state uses mask + minv; /json/info exposes available mask IDs.
  • UI: adds “Mask 🌜” dropdown and “Invert mask 🌜”

Segmask.json

Masks are defined by 1/0 values in a list similar to ledmapN.json files:

{"w":16,"h":32,"mask":[0,0,0,1,1,1,0,0,0,0,...,0,1,1],"inv":false}
  • w: Mask width
  • h: Mask height
  • mask: JSON array of bits
  • inv: Invert mask by default (can be changed at runtime in the UI)

Other Notes

  • I'd appreciate confirmation that this works on something other than the ESP32-S3 boards I have on hand
  • Performance seems unchanged on three segments with masks over 512 LEDs despite checking each virtual LED on each segment against its segment mask. I'm using bitwise ops here and storing the masks as u_int8_t byte arrays, so lookups and memory footprint remains efficient. Still, I expected a small hit to perf, and I'm seeing a perf gain when enabling segment masks on my device. I'd love someone to double check on a larger installation
  • Documentation PR: Feat: Segment Masks WLED-Docs#13

Summary by CodeRabbit

  • New Features

    • Per-segment masking: discover, select and invert masks from the UI; masks persisted in configs. Platform-aware limit on mask slots.
  • Bug Fixes / Reliability

    • Mask geometry validated at frame start; rendering honors masks across all pixel write paths. Mask state is initialized, cleaned up and synchronized safely during segment lifecycle.

✏️ Tip: You can customize this high-level summary in your review settings.

@coderabbitai
Copy link

coderabbitai bot commented Jan 21, 2026

📝 Walkthrough

Walkthrough

Adds per-segment mask support: segment mask state and lifecycle, filesystem loading/parsing of segmaskN.json, UI controls and JSON (de)serialization, render-time gating for masked pixels (1D/2D), and enumeration/init hooks to register available masks.

Changes

Cohort / File(s) Summary
Header declarations
wled00/FX.h, wled00/wled.h
Added segment mask fields (maskId, maskInvert, _mask, _maskW, _maskH, _maskLen, _maskValid); new Segment methods setMask(), clearMask(), accessors hasMask(), maskAllows(), maskAllowsXY(); added WS2812FX::enumerateSegmasks() and segMasks width conditional on WLED_MAX_SEGMASKS.
Configuration constants
wled00/const.h
Introduced WLED_MAX_SEGMASKS with range guard (4–32) and platform defaults (ESP8266:10, others:16).
Core masking implementation
wled00/FX_fcn.cpp
Implemented Segment::setMask()/clearMask() (FS loading/parsing of segmaskN.json, allocation, validation, synchronization); added WS2812FX::enumerateSegmasks() and segMasks population; integrated mask state into segment lifecycle, copy/move, and synchronization.
2D pixel rendering
wled00/FX_2Dfcn.cpp
Update _maskValid in startFrame() when mask present; added maskAllowsXY() guards in both fast and slow setPixelColorXY() paths to skip masked pixels.
1D rendering gating & render-time checks
wled00/FX_fcn.cpp
Enforced maskAllows(i) gating on 1D pixel writes and added mask-validity checks into relevant render paths.
JSON (de)serialization
wled00/json.cpp
deserializeSegment() reads "mask" and "minv" (clamped/applied/cleared); serializeSegment() writes "mask" and "minv"; serializeInfo() adds a "masks" array.
UI / Frontend
wled00/data/index.js
Added per-segment mask UI controls (selector, invert toggle, info), setMask() and setMaskInv() functions, and integrated mask state into segment render UI and mapping logic.
Initialization / Settings integration
wled00/set.cpp, wled00/wled.cpp
Call strip.enumerateSegmasks() alongside LED map enumeration during settings init and after LED-map load.

Sequence Diagram(s)

sequenceDiagram
    participant UI as Frontend UI
    participant App as WLED App
    participant Seg as Segment
    participant FS as Filesystem
    participant Render as Renderer

    UI->>App: setMask(seg, id)
    App->>App: requestJson({seg:{id,mask}})
    App->>Seg: deserializeSegment() with "mask"
    Seg->>Seg: setMask(maskId)
    Seg->>FS: open segmask{maskId}.json
    FS-->>Seg: return JSON (w,h,inv,bitarray)
    Seg->>Seg: parse, validate, alloc _mask, set _maskValid
    Seg-->>App: mask applied (state updated)
    App->>UI: update UI state

    Note over Render,Seg: During render loop
    Render->>Seg: setPixelColorXY(x,y,color)
    Seg->>Seg: maskAllowsXY(x,y)?
    alt allowed
        Seg->>Seg: apply color
    else masked
        Seg-->>Seg: skip pixel
    end
Loading

Estimated code review effort

🎯 4 (Complex) | ⏱️ ~45 minutes

Suggested labels

enhancement

Suggested reviewers

  • willmmiles
  • softhack007

Poem

🐇 I found a mask beneath a file,

Bits and JSON made me smile,
I hop and load each masked array,
Skipping pixels on my way,
Hoppy lights in masked display ✨

🚥 Pre-merge checks | ✅ 2 | ❌ 1
❌ Failed checks (1 warning)
Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 52.94% which is insufficient. The required threshold is 80.00%. Write docstrings for the functions missing them to satisfy the coverage threshold.
✅ Passed checks (2 passed)
Check name Status Explanation
Description Check ✅ Passed Check skipped - CodeRabbit’s high-level summary is enabled.
Title check ✅ Passed The title 'Feat: Segment masks' clearly and directly summarizes the main change—adding per-segment masking functionality to the codebase.

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

✨ Finishing touches
  • 📝 Generate docstrings

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.

Copy link

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

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

Actionable comments posted: 2

Caution

Some comments are outside the diff and can’t be posted inline due to platform limitations.

⚠️ Outside diff range comments (1)
wled00/FX_fcn.cpp (1)

94-103: Mask reload path missing after copy/assignment.

Copy ctor/assignment null out _mask (and _maskValid) but preserve maskId/maskInvert via memcpy. When rendering, maskAllows() checks if (!_mask || !_maskValid) return true;, so copied segments silently skip mask application even though maskId remains set. There is no automatic reload path—the effect must manually call setMask(maskId) after copying, or maskId should be cleared.

🤖 Fix all issues with AI agents
In `@wled00/FX_fcn.cpp`:
- Around line 253-260: _maskValid is only set once when loading the mask and can
become stale if virtual geometry changes; update the validity check by
recomputing it whenever geometry may change (for example at start of setUp() and
startFrame() or immediately before any mask application routine). Locate where
_maskValid is used (e.g., in FX_fcn::_maskValid checks and any applyMask/paint
routines) and replace the single-time assignment with a runtime check that
compares _maskW/_maskH to calc_virtualWidth()/calc_virtualHeight() (or reassign
_maskValid at the start of setUp()/startFrame()) so the mask validity reflects
current virtual geometry. Ensure no behavioral change besides recomputing
validity.
- Around line 150-176: The clearMask()/setMask() flow can free or replace _mask
while maskAllows() may be reading it on the other core; to fix, serialize the
pointer swap/free with the renderer by acquiring the same mutex used by the
render loop (e.g., segmentMux) around the critical section in Segment::clearMask
and Segment::setMask (before freeing or assigning _mask and updating
_maskLen/_maskW/_maskH/_maskValid/maskId) or alternatively wait for the strip to
be idle using the existing idle/wait API before changing the buffer; locate and
protect the critical sections in Segment::clearMask, Segment::setMask and
anywhere maskAllows reads _mask to prevent use-after-free.
🧹 Nitpick comments (2)
wled00/json.cpp (1)

364-372: Prefer an explicit clear path when mask is 0.
This makes intent obvious and avoids any unintended file load if setMask(0) isn’t a no-op.

♻️ Proposed tweak
 if (elem.containsKey("mask")) { // WLEDMM segment mask id
   int maskVal = elem["mask"] | 0;
   if (maskVal < 0) maskVal = 0;
   uint8_t maskId = constrain(maskVal, 0, WLED_MAX_SEGMASKS-1);
-  if (maskId != seg.maskId || (maskId != 0 && !seg.hasMask())) seg.setMask(maskId);
+  if (maskId == 0) {
+    if (seg.hasMask()) seg.clearMask();
+  } else if (maskId != seg.maskId || !seg.hasMask()) {
+    seg.setMask(maskId);
+  }
 }
 if (elem.containsKey("minv")) { // WLEDMM segment mask invert
   seg.maskInvert = elem["minv"] | seg.maskInvert;
 }
wled00/FX.h (1)

725-741: Consider adding [[gnu::hot]] attribute for hot-path optimization.

The mask accessor logic is correct:

  • Fail-open design (returns true when mask is absent/invalid) prevents black pixels on error
  • Bounds checking prevents buffer overread
  • Bit-packing/unpacking is efficient and correct (LSB-first)

Since maskAllows() and maskAllowsXY() are called for every pixel during rendering, consider adding the [[gnu::hot]] attribute (like progress() at line 692 and currentBri() at line 700) to hint the compiler for optimization.

♻️ Suggested optimization
-    inline bool hasMask(void) const { return _mask != nullptr; } // WLEDMM
-    inline bool maskAllows(uint16_t i) const { // WLEDMM
+    [[gnu::hot]] inline bool hasMask(void) const { return _mask != nullptr; } // WLEDMM
+    [[gnu::hot]] inline bool maskAllows(uint16_t i) const { // WLEDMM
       if (!_mask || !_maskValid) return true;
       if (size_t(i) >= _maskLen) return false;
       // WLEDMM: bit-packed mask (LSB-first): byte = i>>3, bit = i&7
       bool bit = (_mask[i >> 3] >> (i & 7)) & 0x01;
       return maskInvert ? !bit : bit;
     }
-    inline bool maskAllowsXY(int x, int y) const { // WLEDMM
+    [[gnu::hot]] inline bool maskAllowsXY(int x, int y) const { // WLEDMM
       if (!_mask || !_maskValid) return true;
       if (x < 0 || y < 0) return false;
       size_t idx = size_t(x) + (size_t(y) * _maskW);
       if (idx >= _maskLen) return false;
       // WLEDMM: row-major (x + y*w), bit-packed mask (LSB-first in each byte)
       bool bit = (_mask[idx >> 3] >> (idx & 7)) & 0x01;
       return maskInvert ? !bit : bit;
     }

Copy link

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

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

Actionable comments posted: 0

Caution

Some comments are outside the diff and can’t be posted inline due to platform limitations.

⚠️ Outside diff range comments (1)
wled00/FX_fcn.cpp (1)

94-103: Reset mask ID and invert flag when clearing mask buffer on segment copy.

After memcpy, both the copy constructor and copy assignment operator null _mask and reset mask buffer state, but leave maskId and maskInvert from the source. This causes the copied segment to report a mask ID that has no actual buffer applied. Reset these to match clearMask() behavior:

Fix for both locations
   _maskW = 0; // WLEDMM
   _maskH = 0; // WLEDMM
   _maskValid = false; // WLEDMM
+  maskId = 0; // WLEDMM
+  maskInvert = false; // WLEDMM

Copy link

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

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

Actionable comments posted: 1

🤖 Fix all issues with AI agents
In `@wled00/FX_fcn.cpp`:
- Around line 171-176: Segment::setMask currently calls clearMask() but proceeds
even if clearMask failed to release the existing mask, which can leak the old
buffer; after calling clearMask() in Segment::setMask, check the _mask member
and abort (return false) if it is still non-null to avoid overwriting/leaking
the previous buffer—use the existing Segment::clearMask() call, then immediately
guard with a check on _mask before continuing (also preserve the existing id==0
behavior).

Comment on lines +171 to +176
bool Segment::setMask(uint8_t id) { // WLEDMM
clearMask();
if (id >= WLED_MAX_SEGMASKS) {
return false;
}
if (id == 0) return true;
Copy link

Choose a reason for hiding this comment

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

⚠️ Potential issue | 🟠 Major

Abort mask load if clearMask() couldn't clear.

If clearMask() fails to acquire segmentMux, _mask can remain non-null; setMask() can then overwrite it, leaking the old buffer. Add a guard to bail out when _mask is still set.

🛠️ Suggested guard
 bool Segment::setMask(uint8_t id) { // WLEDMM
   clearMask();
+  if (_mask) {
+    DEBUG_PRINTLN(F("Segment::setMask: clearMask failed, aborting."));
+    return false;
+  }
   if (id >= WLED_MAX_SEGMASKS) {
     return false;
   }
🤖 Prompt for AI Agents
In `@wled00/FX_fcn.cpp` around lines 171 - 176, Segment::setMask currently calls
clearMask() but proceeds even if clearMask failed to release the existing mask,
which can leak the old buffer; after calling clearMask() in Segment::setMask,
check the _mask member and abort (return false) if it is still non-null to avoid
overwriting/leaking the previous buffer—use the existing Segment::clearMask()
call, then immediately guard with a check on _mask before continuing (also
preserve the existing id==0 behavior).

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