Skip to content

Live data override breaks gamma correction #5661

Closed

Description

@SirDella

What happened?

I updated from 0.15.4 to 0.16 and noticed that my presets looked different. WLED wasn't applying gamma correction while Live Data Override was on.

To Reproduce Bug

  • Select a solid color
  • Start a live data stream (in my case, Hyperion)
  • Override the live data
  • Close the data stream

Expected Behavior

Colours should become dull when applying the override, looking the same way they would if gamma correction was off. Closing the data stream should make gamma correction work again.

Install Method

Binary from WLED.me

What version of WLED?

0.16.0

Which microcontroller/board are you seeing the problem on?

ESP32

Relevant log/trace output

Anything else?

No response

Code of Conduct

  • I agree to follow this project's Code of Conduct

Activity

  1. DedeHai commented on Jun 3, 2026

    @DedeHai
    Collaborator

    @coderabbitai please analyze the regression.

  2. coderabbitai commented on Jun 3, 2026

    @coderabbitai
    Contributor
    🧩 Analysis chain

    🏁 Script executed:

    #!/bin/bash
    gh issue view 5661 --repo wled/WLED --json title,body,comments,labels,assignees,createdAt,updatedAt

    Length of output: 1690


    🏁 Script executed:

    #!/bin/bash
    # Find files related to live data / E1.31 / DDP and gamma correction
    echo "=== Files with 'liveOverride' or 'realtimeOverride' ==="
    rg -rn "liveOverride\|realtimeOverride\|live_override\|liveMode\|realtimeMode" --type cpp -C2
    
    echo ""
    echo "=== Files with gamma correction ==="
    rg -rn "gamma\|gammaCorrect\|correctGamma" --type cpp -l
    
    echo ""
    echo "=== Gamma + live together ==="
    rg -rn "gamma" --type cpp -C2 | grep -i "live\|override\|realtime" | head -40

    Length of output: 967


    🏁 Script executed:

    #!/bin/bash
    # Find the git log of changes between 0.15.x and 0.16 related to live/gamma
    git log --oneline --all | head -30
    echo ""
    echo "=== Tags ==="
    git tag | grep -E "0\.15|0\.16" | head -20

    Length of output: 2078


    🏁 Script executed:

    #!/bin/bash
    echo "=== arlsDisableGammaCorrection context ==="
    rg -n "arlsDisableGammaCorrection" -C5
    
    echo ""
    echo "=== realtimeMode context ==="
    rg -n "realtimeMode" -C3
    
    echo ""
    echo "=== FX_fcn.cpp gamma section full context ==="
    rg -n "gamma\|realtimeMode\|arlsDisable" wled00/FX_fcn.cpp -C5
    
    echo ""
    echo "=== live override / forceOn / arlsForceOn ==="
    rg -n "arlsForce\|forceOn\|liveOverride\|override" --type cpp -C3

    Length of output: 18576



    @DedeHai Here is the regression analysis:

    Root Cause Analysis: "Live data override breaks gamma correction"

    The Bug Location

    wled00/FX_fcn.cpp, line 1741:

    uint32_t c = _pixels[i];
    if (c > 0 && !(realtimeMode && arlsDisableGammaCorrection))
        c = gamma32(c); // apply gamma correction

    What Goes Wrong

    When Live Data Override is active (realtimeOverride > REALTIME_OVERRIDE_NONE), two things happen:

    1. Line 1716 correctly routes rendering through WLED's own segment pipeline (not live data):

      if (realtimeMode == REALTIME_MODE_INACTIVE || useMainSegmentOnly || realtimeOverride > REALTIME_OVERRIDE_NONE) {
          memset(_pixels, 0, ...); // use normal segment rendering
    2. But line 1741 does NOT account for override — realtimeMode is still non-zero (the source stream is still connected in the background), and arlsDisableGammaCorrection defaults to true. So:

      • !(realtimeMode && arlsDisableGammaCorrection) = !(true && true) = false
      • gamma32() is never called → output looks dull/uncorrected, even though WLED is rendering its own effects

    Why This Pattern Is Inconsistent

    Every other realtimeMode guard in the codebase also checks realtimeOverride. Examples:

    • wled00/wled.cpp:109: if (!realtimeMode || realtimeOverride || ...) ✅
    • wled00/led.cpp:68 (the analogous arlsForceMaxBri flag): if (realtimeOverride || !(realtimeMode && arlsForceMaxBri)) ✅
    • wled00/FX_fcn.cpp:1741 (the gamma flag): if (c > 0 && !(realtimeMode && arlsDisableGammaCorrection)) ❌ — missing realtimeOverride check

    The Fix

    // Before (broken):
    if (c > 0 && !(realtimeMode && arlsDisableGammaCorrection))
    
    // After (fixed):
    if (c > 0 && !(realtimeMode && !realtimeOverride && arlsDisableGammaCorrection))
        c = gamma32(c);

    This mirrors the pattern used in led.cpp for arlsForceMaxBri. When override is active, realtimeOverride > 0 makes !realtimeOverride false, collapsing the inhibit condition and allowing gamma to be applied normally.

    Summary

    State realtimeMode realtimeOverride Current gamma? Correct gamma?
    No live source 0 0 ✅ applied ✅ applied
    Live source, no override >0 0 ❌ skipped ❌ skipped (source handles it)
    Live source + override active >0 >0 ❌ skipped (bug) ✅ should apply
    After stream closes 0 0 ✅ applied ✅ applied
  3. DedeHai commented on Jun 3, 2026

    @DedeHai
    Collaborator

    @coderabbitai how is realtimeOverride ended? and what is the difference between "override once" and "override until reboot" ?

  4. coderabbitai commented on Jun 3, 2026

    @coderabbitai
    Contributor
    🧩 Analysis chain

    🏁 Script executed:

    #!/bin/bash
    echo "=== REALTIME_OVERRIDE constants ==="
    rg -n "REALTIME_OVERRIDE" -C2
    
    echo ""
    echo "=== All assignments to realtimeOverride ==="
    rg -n "realtimeOverride\s*=" -C4
    
    echo ""
    echo "=== exitRealtime / realtimeTimeout / realtimeEnd ==="
    rg -n "exitRealtime\|realtimeTimeout\|realtimeEnd\|realtimeActive" -C4
    
    echo ""
    echo "=== realtimeOverride in wled.h or similar header ==="
    rg -n "realtimeOverride" wled00/wled.h -C3 2>/dev/null || rg -n "realtimeOverride" --type cpp -l

    Length of output: 5499



    @DedeHai Here's how it works:

    How realtimeOverride is ended

    The key is exitRealtime() in wled00/udp.cpp (line 442). It's called when a live stream session ends (timeout expiry or source disconnects). Inside it:

    void exitRealtime() {
      if (!realtimeMode) return;
      if (realtimeOverride == REALTIME_OVERRIDE_ONCE) realtimeOverride = REALTIME_OVERRIDE_NONE; // ← only clears ONCE
      strip.setBrightness(bri, true);
      realtimeTimeout = 0;
      realtimeMode = REALTIME_MODE_INACTIVE;
      realtimeIP[0] = 0;
    }

    REALTIME_OVERRIDE_ALWAYS is never cleared by exitRealtime() — it just stays set until the device reboots (or an explicit API/UI call sets lor=0).


    Difference between the two modes

    Value Constant Behaviour
    1 REALTIME_OVERRIDE_ONCE Overrides the current live stream session only. When the stream ends and exitRealtime() fires, the flag is automatically reset to REALTIME_OVERRIDE_NONE. The next live stream will show live data normally.
    2 REALTIME_OVERRIDE_ALWAYS Override persists indefinitely across all future stream connections. Every subsequent stream (E1.31, DDP, etc.) will also be overridden. Only clears on reboot or an explicit lor=0 API call.

    So in both modes WLED renders its own effects (ignoring incoming pixel data) while realtimeMode is active. The only difference is what happens when the stream stops: ONCE self-cleans and behaves normally for the next stream; ALWAYS keeps suppressing live data until you deliberately turn it off.

    This is also the reason the prior learning noted that realtimeOverride must not be persisted to cfg.json — ALWAYS would bake a stale override into every boot.


    🧠 Learnings used
    Learnt from: willmmiles
    Repo: wled/WLED PR: 0
    File: :0-0
    Timestamp: 2026-05-06T19:15:29.642Z
    Learning: In WLED, `realtimeOverride` (`wled00/wled.h`) is an intentionally ephemeral runtime property and must NOT be persisted to `cfg.json`. Persisting it would cause excessive flash wear (it changes frequently as lor is toggled) or mysterious boot-state drift (stale value baked in at last cfg save). The correct fix for boot-preset `lor` unreliability is to apply the boot preset JSON synchronously in `WLED::setup()` before entering the main loop, bypassing the deferred `presetToApply`/`handlePresets()` mechanism which exists only for runtime JSON buffer contention management.
    

    Learnt from: DedeHai
    Repo: wled/WLED PR: 4798
    File: wled00/FX.cpp:7531-7533
    Timestamp: 2025-08-26T11:51:21.817Z
    Learning: In WLED PR `#4798`, DedeHai confirmed that certain gamma-related calls in FX.cpp/FX_fcn.cpp/particle systems are intentional for effect-level shaping (e.g., brightness curves, TV sim, Pride 2015 pre-mix), distinct from final output gamma. Do not flag or remove these in future reviews; add comments when feasible to clarify intent.
    

    Learnt from: softhack007
    Repo: wled/WLED PR: 0
    File: :0-0
    Timestamp: 2026-05-18T21:46:16.718Z
    Learning: In WLED issue `#5619`, the root cause of relay not turning off after HyperHDR stops was confirmed: the HyperHDR-controlled WLED node (Node A) correctly broadcasts bri=0 after exitRealtime(). However, with recv.bri=true and other WLED nodes on the same sync group that are independently ON (bri>0), any state change on those nodes after the 1-second notificationSentTime suppression window overwrites Node A's bri to non-zero, re-enabling the relay. The OS socket buffer stale-packet risk is NOT credible when WLED runs at 30fps realtime (fast loop drains the buffer continuously). The fix is to put the HyperHDR-controlled WLED in a separate sync group or disable recv.bri on it.
    

    Learnt from: softhack007
    Repo: wled/WLED PR: 0
    File: :0-0
    Timestamp: 2026-03-08T00:57:36.134Z
    Learning: In WLED (wled00/cfg.cpp), `deserializeConfig()` is called with an empty JsonObject when cfg.json doesn't exist on fresh install. Any value read without the ArduinoJSON `|` fallback operator or CJSON macro will override correct constructor defaults with 0/null. Known affected values: `strip.setTargetFps(hw_led["fps"])` at line 179 (sets FPS to 0/unlimited instead of WLED_FPS=42). Fix: `strip.setTargetFps(hw_led["fps"] | WLED_FPS)`. The gamma issue (gammaCorrectCol/Bri) had the same root cause and was fixed in commit d1d9dec402 (Jan 2026) using inline `| default` fallbacks.
    

    Learnt from: softhack007
    Repo: wled/WLED PR: 0
    File: :0-0
    Timestamp: 2026-05-11T21:39:46.794Z
    Learning: In WLED v0.16.0 FX.cpp, the following effects directly compute RGB colors without palettes and need gamma8inv() to restore v0.15.0 visual behavior due to the new gamma pipeline: (1) mode_DJLight - CRGB(fftResult/2); (2) mode_2Dmatrix - hardcoded RGBW32(175,255,175,0)/RGBW32(27,130,39,0) default Matrix green; (3) mode_traffic_light - hardcoded 0x00FF0000/0x00EECC00/0x0000FF00; (4) mode_2DFunkyPlank - CHSV(fftResult,255,map(fftResult,0,255,10,255)) where the v channel needs gamma8inv(); (5) mode_waterfall peak indicator CRGB(CHSV(92,92,92)) where v=92 needs gamma8inv(). Separate bug: mode_tv_simulator applies gamma8() manually in both v0.15.0 AND current, causing double gamma in v0.16.0 - fix is to REMOVE the 3 explicit gamma8() calls at the nr/ng/nb assignments, not to add gamma8inv(). Already correctly handled: mode_pride_2015 (has gamma32inv()) and mode_2DDistortionWaves (manual gamma8 removed, pipeline handles it).
    

    Learnt from: softhack007
    Repo: wled/WLED PR: 0
    File: :0-0
    Timestamp: 2026-05-18T21:27:01.781Z
    Learning: In WLED 0.16.0 (d337c8a), toggleOnOff() in led.cpp always sets stateChanged=true. When {"on":false,"live":false} is received from HyperHDR (no "bri" key), the on:false path calls toggleOnOff() setting bri=0 AND stateChanged=true, ensuring stateUpdated(CALL_MODE_DIRECT_CHANGE) IS called and bri=0 IS broadcast via notify(). The earlier analysis suggesting stateChanged would stay false for this path was incorrect.
    

    Learnt from: BobLoeffler68
    Repo: wled/WLED PR: 5440
    File: usermods/user_fx/user_fx.cpp:1307-1327
    Timestamp: 2026-03-24T07:59:28.661Z
    Learning: In WLED's Dissolve Plus effect (usermods/user_fx/user_fx.cpp, mode_dissolveplus), when the "Last one" checkbox (check3/lastOneMode) is turned off while the effect is in PHASE_PAUSE_SURVIVOR, the phase is intentionally NOT immediately reset. The pause expires naturally via the normal delay timing (a few hundred ticks), after which the filling phase begins. PHASE_DISSOLVE_SURVIVOR is reset to PHASE_DISSOLVE and PHASE_FILL_SURVIVOR is reset to PHASE_FILL on toggle-off, but PHASE_PAUSE_SURVIVOR is left to expire on its own. Do not flag this as a bug in future reviews.
    

    Learnt from: softhack007
    Repo: wled/WLED PR: 0
    File: :0-0
    Timestamp: 2026-05-17T12:32:27.834Z
    Learning: In WLED 0.16 (d337c8a), a regression for relay behavior exists when receiving {"on":false,"live":false} (no bri field): the stateChanged flag is checked against bri BEFORE toggleOnOff() is called (which sets bri=0), so stateChanged stays false, and stateUpdated() is skipped. In WLED 0.15, stateUpdated() was always called unconditionally. The fix is to add stateChanged=true after toggleOnOff() in deserializeState(), or to include a bri field in the shutdown payload.
    

    Learnt from: softhack007
    Repo: wled/WLED PR: 0
    File: :0-0
    Timestamp: 2026-05-17T16:30:07.598Z
    Learning: In WLED 16.0.0 twinklefox_base() in wled00/FX.cpp, bg = gamma32inv(bg) applied to SEGCOLOR(1) is incorrect — it over-brightens the background because SEGCOLOR values are sRGB-encoded and the output pipeline already applies gamma32() to compensate. The correct approach is to leave bg unmodified for setPixelColor() output. For the deltabright brightness comparison, since c from gamma-cleaned palettes is in linear space while bg (raw sRGB) is not, the comparison can be made consistent by converting c to sRGB-like space: CRGBW cc2 = gamma32inv(c); cbright = cc2.getAverageLight().
    

    Learnt from: softhack007
    Repo: wled/WLED PR: 0
    File: :0-0
    Timestamp: 2026-05-18T22:06:57.910Z
    Learning: In WLED issue `#5619`, analysis of the user's presets.json confirmed no playlists, timers, or scheduled entries exist. Within WLED itself, there is no purely automatic mechanism for a Node B/C/D to spontaneously emit bri>0 notifications after receiving and applying bri=0 from Node A via sync. WLED has no periodic heartbeat broadcast — notify() is only called on explicit state changes. The relay-stays-on symptom requires an external trigger: user interaction with another device, a home automation hub reacting to WLED state changes, or (as a background amplifier) UDP packet loss leaving some nodes at bri=255.
    
  5. softhack007 commented on Jun 3, 2026

    @softhack007
    Member

    @coderabbitai arlsDisableGammaCorrection is a user option for realtime streaming - it means "Disable realtime gamma correction". When users activate this option, it is expected that no gamma correction is applied for streamed pixels. 🤔 Actually I'm not sure if "no gamma" should also be applied for other segments when "Use main segment only" is selected.

    Please check if your initial analysis is still sound.

  6. coderabbitai commented on Jun 3, 2026

    @coderabbitai
    Contributor
    🧩 Analysis chain

    🏁 Script executed:

    #!/bin/bash
    echo "=== FX_fcn.cpp around line 1700-1760 ==="
    sed -n '1690,1770p' wled00/FX_fcn.cpp
    
    echo ""
    echo "=== useMainSegmentOnly definition and usage ==="
    rg -n "useMainSegmentOnly" -C3
    
    echo ""
    echo "=== arlsDisableGammaCorrection - all usages ==="
    rg -n "arlsDisableGammaCorrection" -C6

    Length of output: 20222



    @softhack007 Good catch — the clarification changes the precision of the analysis, so let me address both points directly.

    Does the initial analysis hold?

    Yes, for the primary case (non-useMainSegmentOnly). The reasoning stands:

    • arlsDisableGammaCorrection = "the streaming source already handles gamma for its pixels". When realtimeOverride > 0, the _pixels buffer is populated by WLED's own segment renderer (line 1716 takes the WLED path). Those are not streamed pixels — the source's gamma-handling is irrelevant — so suppressing gamma32() is wrong.
    • The proposed fix is still correct:
      // "skip gamma only when realtimeMode is active AND no override AND source handles it"
      if (c > 0 && !(realtimeMode && !realtimeOverride && arlsDisableGammaCorrection))
          c = gamma32(c);

    The useMainSegmentOnly nuance

    This is a separate, pre-existing design limitation that the fix above does not resolve, and here's why:

    From set.cpp lines 1247–1249 and json.cpp lines 443–445:

    if (realtimeMode && useMainSegmentOnly) {
        strip.getMainSegment().freeze = !realtimeOverride;
        realtimeOverride = REALTIME_OVERRIDE_NONE;  // always forced back to 0
    }

    In useMainSegmentOnly mode, override is expressed as freeze=false on the main segment, and realtimeOverride is always reset to 0. So !realtimeOverride is always true in that path, and my fix would still skip gamma there.

    But the real ambiguity you're pointing at is this: with useMainSegmentOnly active, line 1716 renders all segments (because useMainSegmentOnly is true in the condition), but only the main segment carries live-streamed pixels. Non-main segments are WLED-generated and shouldn't have gamma suppressed by arlsDisableGammaCorrection. The current code applies the gamma decision globally, not per-pixel, so it can't distinguish:

    Segment Pixel origin Correct gamma? What code does
    Main (frozen, live active) Live stream ❌ skip (source handles it) ❌ skip ← correct
    Non-main WLED effects ✅ apply ❌ skip ← wrong
    Main (unfrozen, override) WLED effects ✅ apply ❌ skip ← wrong

    This is a deeper design issue — a per-pixel origin flag would be needed to fix it properly. The realtimeOverride fix addresses the more common regression (non-useMainSegmentOnly + override), while the useMainSegmentOnly gamma behavior for non-main segments remains a pre-existing limitation worth a separate issue if deemed worth fixing.

    🐇 🤔

  7. added a commit that references this issue on Jun 4, 2026
    f984770
  8. added
    confirmed
    on Jun 4, 2026
  9. softhack007 commented on Jun 4, 2026

    @softhack007
    Member
    // Before (broken):
    if (c > 0 && !(realtimeMode && arlsDisableGammaCorrection))
        c = gamma32(c);
    
    // After (fixed):
    if (c > 0 && !(realtimeMode && !realtimeOverride && arlsDisableGammaCorrection))
        c = gamma32(c);

    I think this fix is correct, we always use the pattern realtimeMode && !realtimeOverride when checking if realtime LEDs are received.
    The other problem - useMainSegmentOnly means that only one segment does not need gamma adjustment - seems to be a heavier lift, should be adressed separately.

  10. DedeHai commented on Jun 4, 2026

    @DedeHai
    Collaborator

    The other problem - useMainSegmentOnly means that only one segment does not need gamma adjustment - seems to be a heavier lift, should be adressed separately.

    there is a good reason gamma is not applied on a segment level - they can overlap which would apply it multiple times for those pixels. Not sure that can be solved cleanly.

  11. softhack007 commented on Jun 5, 2026

    @softhack007
    Member

    True, especially when the "main segment" can be overlapping with other segments. That scenario seems almost impossible to solve cleanly. I agree the segment buffers should stay gamma-free.

    One possibility - but a dirty hack - would be to keep gamma correction on in the "main segment only" case, and convert all pixels with gamma32inv during setRealtimePixel().

    Edit:

    the dirty hack could be added here:

    WLED/wled00/FX_fcn.cpp

    Lines 1762 to 1764 in dea6ec0

    void WS2812FX::setRealtimePixelColor(unsigned i, uint32_t c) {
    if (useMainSegmentOnly) {
    const Segment &seg = getMainSegment();

              if (arlsDisableGammaCorrection) c = gamma32inv(c);

    if (seg.isActive() && i < seg.length()) seg.setPixelColorRaw(i, c);

    This way we lose a bit of accuracy in "main segment only" mode (compared to direct painting to strip), but the result would be compatible with segment blending and all other segments would work as they should.

  12. added a commit that references this issue on Jun 8, 2026
    79ea6ed
  13. added this to the 16.1 milestone on Jun 11, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    bugconfirmed

    Type

    No type

    Projects

    No projects

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions