Skip to content

Gravimeter: bars turn black at full volume (uint8_t(segmentSampleAvg*8) overflows) #5891

Closed

Description

@gilbrit

What happened?

With the AudioReactive Gravimeter effect, the meter tracks volume normally until it reaches the top. At that point every bar goes (almost) black and only the peak/gravity pixel stays lit. At full volume the whole segment is dark except that one pixel.

Versions

16.0.1 (ESP32 release build)
Same code on main @ d2c00c5

To Reproduce Bug

Setup
ESP32-PICO-D4 (M5Stack Atom Echo), built-in PDM mic (SPM1423), AGC on. SK6812 RGBW. Seen on an 8×8 matrix with 1D→2D "Bar" mapping, but the cause doesn't depend on the mapping, so 1D strips are affected too.

Steps to reproduce

Select Gravimeter with default intensity (128) and a black secondary colour (the default).
Play loud audio so the meter reaches the top of the segment.
The bars disappear, and only the peak pixel remains.

Cause
In mode_gravcenter_base(), Gravimeter mode (FX.cpp#L6856 @ v16.0.1):

SEGMENT.setPixelColor(i, color_blend(SEGCOLOR(1), SEGMENT.color_from_palette(index, false, PALETTE_SOLID_WRAP, 0), uint8_t(segmentSampleAvg*8)));

For Gravimeter, segmentSampleAvg = volumeSmth * intensity / 255 * 0.25, which can reach about 63.75. The bar height mapf(segmentSampleAvg2, 0, 64, 0, SEGLEN-1) reaches full height at segmentSampleAvg == 32, which is exactly where segmentSampleAvg8 passes 255. Casting that out-of-range float to uint8_t wraps on ESP32 (it's undefined behaviour in C++). The blend amount drops to near 0, so every bar becomes SEGCOLOR(1) (black by default). The peak pixel is drawn straight from the palette, so it stays lit.

Gravcenter, Gravcentric and Gravfreq use the same expression but scale by 0.125, which tops out at about 31.9, so they don't overflow.

Suggested fix
Clamp before the cast:

uint8_t(fminf(segmentSampleAvg * 8.0f, 255.0f))

The same clamp could go on the Gravcenter line (#L6878–6879) for safety.

Workaround
Noisemeter has no such overflow, or keep Gravimeter's intensity below 128 (but then it never reaches the top row).

Expected Behavior

At max intensity, all lights should be lit, rather than the top row of the matrix only.

Install Method

Self-Compiled

What version of WLED?

16.0.1 (ESP32 release build)

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 Oct 8, 2026

    @DedeHai
    Collaborator

    @coderabbitai is this a regression that was recently introduced or is this intended behaviour of the effect?

  2. coderabbitai commented on Oct 8, 2026

    @coderabbitai
    Contributor
    🧩 Analysis chain

    🏁 Script executed:

    #!/bin/bash
    set -euo pipefail
    gh issue view 5891 --repo wled/WLED --json title,body,createdAt,url,comments

    Length of output: 3457


    🏁 Script executed:

    #!/bin/bash
    set -euo pipefail
    ast-grep outline wled00/FX.cpp --match 'mode_gravcenter_base|mode_gravimeter|mode_gravcenter|mode_gravcentric|mode_gravfreq' --view expanded
    rg -n -C 12 'segmentSampleAvg\s*\*\s*8|mode_gravcenter_base|segmentSampleAvg\s*=.*0\.(125|25)' wled00/FX.cpp
    git rev-parse --is-shallow-repository
    git tag --list 'v*' | tail -35
    git log -n 20 --format='%h %ad %s' --date=short -- wled00/FX.cpp

    Length of output: 7885


    🏁 Script executed:

    #!/bin/bash
    set -euo pipefail
    sed -n '6854,6908p' wled00/FX.cpp
    git blame -L 6868,6888 wled00/FX.cpp
    git blame -L 6901,6908 wled00/FX.cpp
    git log -n 12 --format='%H %ad %s' --date=short -S 'uint8_t(segmentSampleAvg*8)' -- wled00/FX.cpp
    git log -n 12 --format='%H %ad %s' --date=short -S 'mode_gravcenter_base' -- wled00/FX.cpp
    gh api repos/wled/WLED/tags --paginate --jq '.[] | select(.name | test("^v(0\\.)?(14|15|16)")) | [.name,.commit.sha] | @tsv'

    Length of output: 8744


    🏁 Script executed:

    #!/bin/bash
    set -euo pipefail
    git show 07cc3aa5c -- wled00/FX.cpp | sed -n '/Gravcenter/,/JUGGLES/p'
    git show 07cc3aa5c^:wled00/FX.cpp | grep -n -A65 -B5 'mode_gravimeter('
    git show 26397ee8 -- wled00/FX.cpp | grep -n -A8 -B8 'segmentSampleAvg'
    for item in \
     'v0.14.0:3847bfc41aa66af8b7268f685e53429109d8baae' \
     'v0.15.0:faadb67eb0a108ac947beb60624ccca66b2b1e70' \
     'v0.15.1:4f3992b4dc57c888b53d9576c894a278e03e4cfc' \
     'v16.0.1:29b389df1c1aaec6ff53aea742d17063b985906c'; do
      name="${item%%:*}"; sha="${item#*:}"
      echo "=== $name ==="
      git show "$sha:wled00/FX.cpp" | grep -n -A52 -B2 -E '(uint16_t|void) mode_gravimeter\(|(uint16_t|void) mode_gravcenter_base\('
    done
    gh pr view 4145 --repo wled/WLED --json title,body,mergedAt,url

    Length of output: 77275


    🏁 Script executed:

    #!/bin/bash
    set -euo pipefail
    git grep -n -A30 -B3 -E 'uint32_t color_blend\(' faadb67eb0a108ac947beb60624ccca66b2b1e70 -- '*.cpp' '*.h'
    git grep -n -A30 -B3 -E 'uint32_t color_blend\(' 3847bfc41aa66af8b7268f685e53429109d8baae -- '*.cpp' '*.h'

    Length of output: 14566


    @DedeHai This is a bug, not intended effect behavior. The specific blackout at full height traces to #4245 in December 2024, rather than a recent 16.0.1 change.

    The history shows:

    • v0.14.0, v0.15.0, and v0.15.1 already used segmentSampleAvg *= 0.25 and passed segmentSampleAvg*8 without clamping. However, the old color_blend() accepted a uint16_t. At a blend value of 256 with a black secondary color, it still produced the palette color.
    • #4245, commit 26397ee8, added the explicit uint8_t(segmentSampleAvg*8) conversion. At full meter height, segmentSampleAvg reaches 32, so the conversion receives 256. That explains the reported ESP32 wrap to zero and the black bars.
    • #4145 merged the gravity effects into mode_gravcenter_base(). It preserved the problematic conversion; it did not introduce it.

    There was already a range-handling defect in the older code. #4245 changed how that defect appears at the full-height threshold.

    The proposed clamp is appropriate:

    uint8_t(fminf(segmentSampleAvg * 8.0f, 255.0f))

    This conclusion comes from source history. I did not reproduce the effect on hardware.

    You are interacting with an AI system.

  3. softhack007 commented on Oct 8, 2026

    @softhack007
    Member

    In the old version of gravimeter, the overflow was intended behaviour - it produces a nice "hit the bar" effect in color_from_palette.

  4. DedeHai commented on Oct 8, 2026

    @DedeHai
    Collaborator

    @softhack007 I quickly checked but could not pinpoint on how that mechanism used to work, it seems a bit hacky. any Idea on how to make it behave as it was?

    edit: I checked and cooked up a solution, please review

  5. DedeHai commented on Oct 8, 2026

    @DedeHai
    Collaborator

    @coderabbitai please check if there are other places where color_blend() may have been used with overflows prior to #4245

  6. coderabbitai commented on Oct 8, 2026

    @coderabbitai
    Contributor
    🧩 Analysis chain

    🏁 Script executed:

    #!/bin/bash
    set -euo pipefail
    gh pr view 4245 --repo wled/WLED --json title,body,mergeCommit,url
    git show --stat 26397ee8ad675ef6c19cb4c2be70009166926c76
    git grep -n -E '\bcolor_blend[[:space:]]*\(' 26397ee8^ -- '*.cpp' '*.h'
    git show 26397ee8 -- wled00/FX.cpp

    Length of output: 40954


    🏁 Script executed:

    #!/bin/bash
    set -euo pipefail
    tmp=$(mktemp -d)
    git show 26397ee8^:wled00/FX.cpp > "$tmp/FX.cpp"
    git show 26397ee8^:wled00/colors.cpp > "$tmp/colors.cpp"
    ast-grep outline "$tmp/FX.cpp" --match 'mode_breath|twinklefox_base|mode_exploding_fireworks|mode_drip|mode_ripplepeak|mode_gravcenter|mode_gravimeter|mode_juggles|mode_matripix|mode_pixelwave|mode_pixels|mode_blurz|mode_freqmap|mode_freqpixels|mode_noisemove|mode_waterfall|mode_freqwave|mode_freqmatrix' --view expanded
    ast-grep outline "$tmp/colors.cpp" --match color_blend --view expanded
    sed -n '1,65p' "$tmp/colors.cpp"
    for range in 315,345 2650,2683 3525,3655 3670,3745 6320,6398 6460,6515 6550,6610 6635,6668 6755,6790 6870,6965 6970,7025 7060,7115 7200,7330; do
      sed -n "${range}p" "$tmp/FX.cpp" | cat -n
    done
    git grep -n -E 'volumeSmth[[:space:]]*=|volumeRaw[[:space:]]*=|fftResult\[[^]]+\][[:space:]]*=|FFT_Magnitude[[:space:]]*=' 26397ee8^ -- '*.cpp' '*.h' | head -100
    git show 26397ee8 -- wled00/colors.cpp wled00/FX_2Dfcn.cpp wled00/FX_fcn.cpp

    Length of output: 65510


    🏁 Script executed:

    #!/bin/bash
    set -euo pipefail
    tmp=$(mktemp -d)
    git show 26397ee8^:usermods/audioreactive/audio_reactive.h > "$tmp/audio_reactive.h"
    ast-grep outline "$tmp/audio_reactive.h" --match 'limitSampleDynamics|getSample|agcAvg|loop|process' --view expanded
    git grep -n -C3 -E 'sampleAvg[[:space:]]*=|sampleRaw[[:space:]]*=|sampleAgc[[:space:]]*=|rawSampleAgc[[:space:]]*=|my_magnitude[[:space:]]*=' 26397ee8^ -- usermods/audioreactive/audio_reactive.h
    git grep -n -E '#define RGBW32|color_blend' 26397ee8^ -- ':!*.cpp' ':!*.h'
    git grep -n -E '#define RGBW32' 26397ee8^ -- '*.h'
    python - <<'PY'
    import subprocess
    s=subprocess.check_output(['git','show','26397ee8^:wled00/FX.cpp'],text=True).splitlines()
    ranges=[(165,205),(253,278),(1650,1688),(2470,2515),(3320,3378),(4170,4182),(6795,6820),(328,346)]
    for a,b in ranges:
        print(f'\n=== wled00/FX.cpp {a}–{b} ===')
        for n in range(a,b+1): print(f'{n}: {s[n-1]}')
    PY
    sed -n '930,968p' "$tmp/audio_reactive.h"
    sed -n '1345,1378p' "$tmp/audio_reactive.h"
    git show 26397ee8^:wled00/util.cpp | sed -n '435,530p'
    git rev-parse 26397ee8^

    Length of output: 13129


    🏁 Script executed:

    #!/bin/bash
    set -euo pipefail
    git grep -n -E '#define RGBW32' 26397ee8^ -- '*.h' || true
    python - <<'PY'
    import subprocess
    s=subprocess.check_output(['git','show','26397ee8^:wled00/FX.cpp'],text=True).splitlines()
    ranges=[(165,205),(253,278),(1650,1688),(2470,2515),(3320,3378),(4170,4182),(6795,6820),(328,346)]
    for a,b in ranges:
        print(f'\n=== wled00/FX.cpp {a}–{b} ===')
        for n in range(a,b+1): print(f'{n}: {s[n-1]}')
    a=subprocess.check_output(['git','show','26397ee8^:usermods/audioreactive/audio_reactive.h'],text=True).splitlines()
    for lo,hi in [(835,861),(937,968)]:
        print(f'\n=== audio_reactive.h {lo}–{hi} ===')
        for n in range(lo,hi+1): print(f'{n}: {a[n-1]}')
    u=subprocess.check_output(['git','show','26397ee8^:wled00/util.cpp'],text=True).splitlines()
    for n in range(435,531): print(f'{n}: {u[n-1]}')
    PY
    git rev-parse 26397ee8^

    Length of output: 19776


    @DedeHai Yes. I found other effects that passed blend values above 255 before #4245. I checked the call sites at 217d2aeb, the parent of that change.

    Confirmed cases besides Gravimeter

    All locations below refer to historical wled00/FX.cpp.

    Effect Old blend argument When it exceeds 255 Change in #4245
    Ripple Peak SEGENV.aux0 / ripples[i].state * 2 At state 1, the argument is 510 because SEGENV.aux0 is 255. Replaced it with uint8_t(2*255/state). This also changes integer-division rounding at some later states.
    Blurz 2 * fftResult[...] FFT bin ≥128. Maximum: 510. Added a uint8_t cast.
    Noisemove fftResult[i % 16] * 4 FFT bin ≥64. Maximum: 1020. Added a uint8_t cast.
    Matripix volumeRaw * SEGMENT.intensity / 64 For example, volume 128 and intensity 128 produce 256. Maximum: 1016 for volume 255. Changed pixBri from int to uint8_t.
    Pixelwave Same as Matripix Same range and threshold. Changed pixBri from int to uint8_t.
    Freqmap Integer conversion of FFT magnitude / 4.0f Magnitude ≥1024 produces ≥256. The sound simulator supplies magnitude 1250 when active, so the old argument is 312. Changed the conversion and storage to uint8_t.
    Waterfall Integer conversion of FFT magnitude / 8.0f Magnitude ≥2048 produces ≥256. The audio producer does not impose this upper limit. Changed the cast to uint8_t.
    Freqpixels Integer conversion of FFT magnitude / 16.0f Magnitude ≥4096 produces ≥256. The audio producer does not impose this upper limit. Changed the cast to uint8_t.

    Historical source: Ripple Peak, Matripix, Pixelwave, and FFT effects.

    Additional conditional cases

    • Gravcenter, Line 6507–6508: its blend simplifies to volumeSmth * intensity / 255. Unlike Gravimeter, it stays within 255 for normal 0–255 volume input. However, received audio-sync volume has no upper clamp.
    • Pixels, Line 6915: it passes volumeSmth directly. It can exceed 255 with audio-sync input for the same reason.

    I did not find another comparable case in the remaining inspected calls. Expressions in Twinklefox, Exploding Fireworks, and Drip stay within range through branch conditions or clamps. Calls with b16=true intentionally used the 0–65535 range; those are not overflow cases.

    Why this matters

    The old implementation accepted uint16_t, but its default arithmetic used a blend maximum of 255. It did not clamp larger arguments. RGBW32() then narrowed each calculated channel to a byte.

    That behavior is not equivalent to narrowing the blend argument to a byte first. It is also not equivalent to color_blend16(), which uses a different scale.

    I would prioritize Ripple Peak, Blurz, Noisemove, Matripix, Pixelwave, and Freqmap for compatibility checks. Their out-of-range inputs follow directly from normal effect operation or sound simulation. Source inspection establishes the behavior change, but it does not establish whether each effect intended that behavior.

    Thanks for the clarification about Gravimeter’s intended overflow behavior. My earlier blanket description of that behavior as a defect was too broad. A clamp prevents the blackout, but it does not preserve the old overflow effect.

    This was a source audit. I did not test the effects on hardware.


    ✏️ Learnings added
    Learnt from: DedeHai
    URL: https://github.com/wled/WLED/issues/5891
    
    Timestamp: 2026-10-08T08:39:45.054Z
    Learning: In WLED's historical C++ effect mode_gravimeter() in wled00/FX.cpp, the pre-#4245 out-of-range color_blend() behavior was intentional, according to maintainer softhack007: it produced a "hit the bar" color effect. Do not assume that clamping the blend argument to 255 preserves the intended appearance. Distinguish legacy per-channel arithmetic overflow from narrowing the blend argument to uint8_t.
    

    Note: Learnings are effective only in the context of similar code segments. To apply general coding guidelines, please configure review instructions. You can manage existing learnings in the app.

    You are interacting with an AI system.

  7. added
    confirmed
    on Oct 8, 2026
  8. DedeHai commented on Oct 8, 2026

    @DedeHai
    Collaborator

    @softhack007 some of the FX the rabbit flagged are definitely affected but IMHO for the better (no random colors due to overflow). Some of the flagged ones do not actually overflow in practice. I do not really use AR effects so I can not tell if any others need adjustment. What is your verdict here?

  9. softhack007 commented on Oct 9, 2026

    @softhack007
    Member

    @DedeHai thanks, I'll check the effects on the weekend (had a working week full of meetings 🥵 ).

    Maybe for the other effects, it would be simplest to just clamp blend values to 255, instead of wrapping around by implicit %256. so we'd use max(xx, 255U) instead of uint8_t(xx). I think only gravimeter was explicitly relying on old blend > 255 behaviour.

  10. softhack007 commented on Oct 9, 2026

    @softhack007
    Member

    @coderabbitai related to #5891 (comment) - how did the original colorFromPalette() function and FastLED 3.6.x handle blend values > 255?

  11. coderabbitai commented on Oct 9, 2026

    @coderabbitai
  12. coderabbitai commented on Oct 9, 2026

    @coderabbitai
    Contributor
    🧩 Analysis chain

    🏁 Script executed:

    #!/bin/bash
    set -euo pipefail
    gh api repos/wled/WLED/issues/comments/6056083277 --jq '.body'
    tmp=$(mktemp -d)
    ref=217d2aeb7fce0c5fce45b802a8dada30866f6c18
    for file in FX_fcn.cpp colors.cpp FX.cpp; do
      gh api "repos/wled/WLED/contents/wled00/$file?ref=$ref" -H 'Accept: application/vnd.github.raw+json' > "$tmp/$file"
    done
    gh api 'repos/FastLED/FastLED/contents/src/colorutils.cpp?ref=3.6.0' -H 'Accept: application/vnd.github.raw+json' > "$tmp/colorutils.cpp"
    ast-grep outline "$tmp/FX_fcn.cpp" --match color_from_palette --view expanded
    ast-grep outline "$tmp/colors.cpp" --match color_blend --view expanded
    ast-grep outline "$tmp/FX.cpp" --match mode_gravimeter --view expanded
    ast-grep outline "$tmp/colorutils.cpp" --match 'ColorFromPalette|nblend' --view expanded
    sed -n '1140,1168p' "$tmp/FX_fcn.cpp"
    sed -n '1,40p' "$tmp/colors.cpp"
    sed -n '6550,6605p' "$tmp/FX.cpp"
    sed -n '568,655p' "$tmp/colorutils.cpp"
    rg -n -A12 -B2 'CRGB& nblend|CRGB blend\(' "$tmp/colorutils.cpp"

    Length of output: 28544


    @softhack007 FastLED narrowed integer inputs to 8 bits before processing. The old WLED color_blend() did not. These are different operations.

    I checked FastLED 3.6.0 and the WLED source immediately before #4245.

    FastLED ColorFromPalette()

    The relevant signature was:

    CRGB ColorFromPalette(
        const CRGBPalette16& pal,
        uint8_t index,
        uint8_t brightness,
        TBlendType blendType);

    It had no numeric blend-amount parameter. blendType selected the interpolation mode.

    If an integer above 255 was passed as index or brightness, conversion to uint8_t reduced it modulo 256:

    Integer input Value received
    256 0
    312 56
    510 254
    512 0

    Thus, index 256 selected palette index 0. Brightness 256 became 0 and produced black.

    For interpolation, FastLED calculated f2 = (index & 0x0F) << 4. This weight could not exceed 240. An out-of-range blend weight never reached that calculation.

    FastLED’s separate blend() and nblend() functions also used an 8-bit blend amount (fract8). Integer inputs above 255 narrowed before blending.

    FastLED source

    WLED Segment::color_from_palette()

    The historical wrapper accepted a uint16_t index and a uint8_t brightness.

    If mapping was enabled, it first mapped the index from segment coordinates to palette coordinates. The resulting index then narrowed to 8 bits at scale8() or ColorFromPalette().

    wrap = false did not clamp an oversized index. It restricted interpolation near the palette end.

    WLED wrapper source

    Old WLED color_blend()

    With b16 = false, this function accepted a uint16_t blend, but used a 255-scale calculation:

    ((channel2 * blend) + (channel1 * (255U - blend))) >> 8

    It did not clamp the blend or narrow it to 8 bits first. The calculated channels narrowed afterward.

    For black as color1 and RGB (200, 100, 50) as color2:

    Blend Old WLED result
    256 (200, 100, 50)
    510 (142, 199, 99)

    At 510, the calculated red channel was 398. Narrowing that channel produced 142.

    This last operation produced Gravimeter’s legacy color change. Gravimeter passed segmentSampleAvg * 8 to color_blend(), not to color_from_palette(). Neither FastLED’s 8-bit blending nor clamping to 255 reproduces that behavior.

    Sources: old blending implementation, Gravimeter call.

    One important distinction: modulo-256 conversion applies to integer inputs. Direct conversion of an out-of-range floating-point value to uint8_t has undefined behavior in C++; portable code must not rely on it wrapping.

    You are interacting with an AI system.

  13. softhack007 commented on Oct 9, 2026

    @softhack007
    Member

    Direct conversion of an out-of-range floating-point value to uint8_t has undefined behavior in C++

    @DedeHai this is another important side-note: directly casting a float result that does not fit into uint8_t (float < 0 or float > 255.0) is undefined behaviour - we already had other effects where this did not work on the C3, but it worked on extensa esp32. The portable solution would be to cast through int, for example (uint8_t(int(segmentSampleAvg*8))). It would still wrap-around however, the difference is just that casting trough signed integer removes the undefined behaviour problem.

    If I remember correctly, the scaling hacks were already there in WLED-SR, but I always wanted to replace them so no intermediate down-and-upscaling is needed. The main intention was to use SampleAvg as float and avoid map() - otherwise bars started to behave very jumpy on long LED strips (>125 leds)

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

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions