Skip to content

[Tracking] Break unwanted cross-TU references that drag optional subsystems into all builds (follow-up to #2421) #2424

Closed

Description

@zackees

Summary

Follow-up to #2421. Symbol-level analysis of #2420's reproducer build identified a cascade of unwanted cross-TU references in FastLED's source where core/system modules unconditionally reference symbols from optional subsystems (audio, remote, net, fx, gfx, video, third_party). These references force the linker to pull each optional unity TU into the build for ONE symbol each. --gc-sections then strips most of the code from those TUs but leaves orphan .eh_frame entries behind (~80 KB of pure waste, fixed at the build level by #2423 but at the source level still pulls in non-trivial code).

This issue tracks the source-level cleanup of those references.

Cascade map

                   src.cpp.o (CFastLED)
                       │
                       ▼
            ┌─────────────────────┐
            │ fl.audio+.cpp.o     │──────────┐
            └─────────────────────┘          │
                                             ▼
                                   ┌─────────────────────┐
                                   │ third_party+.cpp.o  │
                                   └─────────────────────┘

    fl.channels+.cpp.o ──────► fl.gfx+.cpp.o
    fl.system+.cpp.o ────────► fl.fx+.cpp.o ─────► fl.video+.cpp.o
    fl.stl+.cpp.o ───────────► fl.net+.cpp.o
    platforms+.cpp.o ────────► fl.remote+.cpp.o

Total .eh_frame orphan bloat from these references: ~107 KB.
Total potential dead code dragged in (before --gc-sections): much larger; depends on how many functions are referenced transitively.

Per-reference findings (file:line precise)

1. src.cpp.o → fl::audio::AudioManager::instance()

Pulls in: libFastLED.a(fl.audio+.cpp.o) — ~34 KB orphan eh_frame
Locations: src/FastLED.cpp.hpp:706, 711, 716, 721

  • L706: CFastLED::add(const fl::audio::Config&)
  • L711: CFastLED::add(fl::shared_ptr<fl::audio::IInput>)
  • L716: CFastLED::add(fl::UIAudio&)
  • L721: CFastLED::remove(fl::shared_ptr<fl::audio::Processor>)

Why: Four overloaded CFastLED methods unconditionally reference the audio singleton. Decorated with FL_MAYBE_UNUSED but not gated by FASTLED_HAS_AUDIO.
Fix: Wrap all four definitions with #if FASTLED_HAS_AUDIO, OR convert to lazy/weak singleton lookup. The corresponding declarations in FastLED.h would also need gating to avoid signature mismatches.

2. fl.channels+.cpp.o → fl::rgb_2_rgbw_exact(...)

Pulls in: libFastLED.a(fl.gfx+.cpp.o) — ~17 KB orphan eh_frame
Location: src/fl/gfx/rgbw.cpp.hpp:116
Why: Global variable initializer rgb_2_rgbw_function g_user_function = rgb_2_rgbw_exact; runs at static-init for every TU that includes the header transitively (which now includes the channels unity TU).
Fix: Defer to lazy init on first call (function-local static), OR initialize to nullptr and have setRgb2RgbwFunction() install the default on first use.

3. fl.system+.cpp.o → fl::Video::begin(fl::shared_ptr<fl::filebuf>)

Pulls in: libFastLED.a(fl.fx+.cpp.o) — ~10 KB orphan eh_frame
Location: src/fl/system/file_system.cpp.hpp:180, in FileSystem::openVideo(...)
Why: Core file-system module unconditionally provides a Video factory method.
Fix: Move openVideo() and related video-loading methods into a separate optional header (fl/system/file_system_video.h) included only when FASTLED_HAS_VIDEO. Or move to a header-only inline template instantiated at the user's call site, NOT inside the system unity TU.

4. fl.fx+.cpp.o → fl::video::VideoImpl::setTimeScale(float)

Pulls in: libFastLED.a(fl.video+.cpp.o) — ~2 KB orphan eh_frame (this one is small)
Location: src/fl/fx/video.cpp.hpp:105, in Video::setTimeScale(float)
Why: Pimpl-style forwarding from Video to VideoImpl requires an out-of-line definition.
Fix: Inline VideoImpl::setTimeScale in the impl header so the call folds at use site, OR collapse the pimpl boundary entirely (it doesn't seem to provide ABI stability in this codebase).

5. fl.stl+.cpp.o → fl::net::http::ChunkedReader::hasChunk()

Pulls in: libFastLED.a(fl.net+.cpp.o) — ~10 KB orphan eh_frame
Location: src/fl/stl/asio/http/http_parser.cpp.hpp:229, in HttpRequestParser::parseBody()
Why: Core STL/ASIO HTTP parser unconditionally calls into the chunked-encoding reader.
Fix: This one is tricky — HTTP parsing IS in the STL module by design. Options: (a) gate chunked-encoding support behind #if FASTLED_HAS_NET_HTTP_CHUNKED, (b) provide a weak __attribute__((weak)) stub of ChunkedReader::hasChunk() returning false in the STL module, with the real implementation in the net module overriding it at link, (c) move the entire asio/http subtree out of STL into net, since HTTP isn't really STL.

6. platforms+.cpp.o → fl::formatJsonResponse(fl::json const&, char const*)

Pulls in: libFastLED.a(fl.remote+.cpp.o) — ~13 KB orphan eh_frame
Location: src/platforms/esp/32/drivers/ble/ble_esp32.cpp.hpp:476, in BLE notification handler lambda (L475-479)
Why: ESP32 BLE driver unconditionally formats responses as JSON via the remote-API helper.
Fix: Wrap the BLE JSON formatting branch with #if FASTLED_HAS_REMOTE, OR provide a weak fallback that returns a minimal text response when remote isn't linked.

7. fl.audio+.cpp.o → apply_kernels

Pulls in: libFastLED.a(third_party+.cpp.o) — ~10 KB orphan eh_frame
Locations: src/fl/audio/fft/fft_impl.cpp.hpp:315, 716, in FftImpl::processConstantQ(...) and inline constant-Q loop
Why: Audio FFT unconditionally calls into the third-party CQ kernel module.
Fix: Gate the constant-Q path behind #if FASTLED_HAS_AUDIO_CONSTANT_Q so users who only want plain FFT don't pay for kernel application code. (This becomes moot if reference #1 is also fixed, since fl.audio wouldn't be linked at all in non-audio sketches.)

8 & 9. Additional fl::audio::fft::Bins references in core STL

Pulls in: Already part of #1's chain, but worth noting because fixing #1 alone may not be sufficient if these stay
Locations:

  • src/fl/stl/string.cpp.hpp:34 — string::append(const audio::fft::Bins&)
  • src/fl/stl/strstream.cpp.hpp:28 — sstream::operator<<(const audio::fft::Bins&)
  • Plus header decl at src/fl/stl/strstream.h:59

Why: Core string-formatting types unconditionally export specialized overloads for an audio type.
Fix: Gate all three with #if FASTLED_HAS_AUDIO, OR move into a separate header fl/stl/string_audio_format.h that only audio code includes.

Common pattern

All nine references share the same shape: core/system modules unconditionally provide convenience APIs that bind to optional subsystem types. The convenience saves the user one call site at the cost of dragging the entire optional subsystem into every build, plus its .eh_frame, plus whatever ESP-IDF dependencies the subsystem registers (BLE → bluedroid stack, audio → I2S driver, net → asio + lwip plumbing).

Priority ranking for fixes

# Reference Fix difficulty Bytes recovered Worth it?
1 CFastLED::add(audio) overloads Easy (4 macro guards) ~34 KB Yes — biggest single win
6 BLE → formatJsonResponse Easy (one macro guard) ~13 KB Yes — easy
5 http_parser → ChunkedReader Medium (architectural choice) ~10 KB Yes — also fixes net stack pull
2 rgbw global initializer Easy (lazy init) ~17 KB Yes — easy
3 FileSystem::openVideo Medium (header reorg) ~10 KB Probably yes
7 FFT apply_kernels Easy (one macro guard) ~10 KB Yes if #1 doesn't already cover it
8/9 string/sstream audio overloads Easy (macro guards) small but enables cleaner #1 fix Yes if doing #1
4 Video::setTimeScale pimpl Easy (inline) ~2 KB Low priority

Combined estimate

If all references are broken cleanly: ~80-100 KB of orphan eh_frame eliminated PLUS ~50-100 KB of actual dead code that --gc-sections was already stripping (so this doesn't directly shrink the binary, but it reduces compile time, link time, and removes the cascading ESP-IDF driver pulls).

This is complementary to #2423 (FL_NO_UNWIND): #2423 makes orphan eh_frame zero-cost in opt-in builds; this issue removes the orphans entirely so all builds benefit, even those that need backtraces enabled.

Suggested execution order

  1. Land feat(fl/stl): add FL_NO_UNWIND macros, apply to ESP32 unity headers #2423 (gives users an immediate opt-in escape hatch)
  2. Tackle reference support TLS3001 #1 (CFastLED::add audio overloads) — biggest single win, smallest blast radius
  3. Tackle references Interrupt short circuit #2, WS2801 Timing issue - Calling FastLED.show() too quickly does not update the LEDs. #6, Support P9813 - AKA Total Lighting Control from CoolNeon #7, Support TM1829 #8, Support LPD1886 w/8bit CRGB #9 in any order — each is independent and small
  4. Tackle reference added ATtiny84 / 44 / 24 support, using pin defs from mellis  #5 (http_parser) — needs architecture decision
  5. Tackle reference Allow duplication of data to more LEDs #3 (FileSystem::openVideo) — needs header reorg
  6. Reference Example: testleds needs updating (find included update) #4 is optional cleanup — small bytes, do during a routine refactor

TODO

  • Open separate PRs for each reference (or grouped by similar fix shape)
  • Validate each fix against the reporter's [Bug] Compounded timing inaccuracy on master compared to 3.10.3 #2420 sketch with bash compile esp32s3 --examples Blink
  • Verify bash test --cpp still passes after each change
  • Check whether FASTLED_HAS_AUDIO / FASTLED_HAS_NET / FASTLED_HAS_REMOTE / FASTLED_HAS_VIDEO macros currently exist; if not, add them (default ON to preserve current behavior, opt-out via FASTLED_NO_AUDIO etc. for size-conscious users)

Activity

  1. zackees commented on May 5, 2026

    @zackees
    MemberAuthor

    Empirical re-verification: cross-TU references mostly do NOT contribute live code

    @zackees was right to push back on this one. I built ESP32-S3 binaries on current master (with #2423 already merged) and ran the actual experiment of removing one of the suspect references. The previous analysis was based on the linker map, which counts contributions to output sections — but that includes orphan .eh_frame entries from --gc-sections-stripped code. The actual flashed binary tells a very different story.

    Methodology

    1. Baseline: bash compile esp32s3 --examples Blink on current master → 830,272 bytes
    2. Treatment: #if 0'd out the four CFastLED::add(audio) / remove(audio) overload definitions in src/FastLED.cpp.hpp:704-722 AND their declarations in src/FastLED.h:798,815,830,858, then rebuilt
    3. Compared section sizes, FDE counts, and symbol presence between baseline and treatment

    Baseline state (current master, default release build)

    Binary size:    830,272 bytes
    .flash.text:    350,916 bytes
    .flash.rodata:  385,900 bytes
    Total FDEs:     6,478  (down from 16,773 in reporter's #2420 ea5d8ec build — 61% reduction from #2423)
    

    Symbol search in the baseline binary for code from the suspect TUs:

    Symbol pattern Count
    fl::audio::* 0
    AudioManager / audio::Processor / audio::IInput / audio::Config 0
    fl::net::* / fl::http::* / ChunkedReader / parseBody / http_parser 0
    fl::Video::* / fl::video::* / FileSystem / openVideo 0
    formatJsonResponse / fl::remote::* / BleDevice / ble_esp32 0
    fl::fft::* / fl::mfcc / i2s_pdm 0
    CFastLED::add(...audio...) / CFastLED::remove(...audio...) (the 4 overloads) 0
    rgb_2_rgbw_* family (5 functions ~434 bytes) 5 ← only one actually in binary
    fl::asio::http::EspRouteContext (small destructors/vector ops ~120 bytes) a few

    --gc-sections is doing its job. The audio/net/video/remote/fx/gfx code is not in the final binary at all on a default release build.

    Treatment delta (audio overloads removed)

    Metric Baseline Treatment Delta
    Binary size 830,272 830,080 -192 bytes
    .flash.text 350,916 350,916 0
    .flash.rodata 385,900 385,708 -192
    Total FDE count 6,478 6,478 0
    Audio symbols in binary 0 0 0

    The entire fl.audio reference cascade saves 192 bytes in a default release build. Not the predicted ~34 KB. The 192 bytes are merged-string-pool entries for the four method symbol names (vtable strings, debug names) that the linker keeps because the methods are declared.

    Why my earlier estimate was wrong

    The previous analysis quoted "~34 KB orphan eh_frame from fl.audio" and similar numbers for fl.remote/net/fx/gfx. Those numbers were from the linker map, where they appeared as input contributions to .flash.rodata. They were real bytes — but they were .eh_frame orphan FDEs, not live code or live data.

    Two things have changed since that analysis:

    1. PR feat(fl/stl): add FL_NO_UNWIND macros, apply to ESP32 unity headers #2423 (FL_NO_UNWIND) merged — strips most .eh_frame from FastLED unity TUs in default release builds. Confirmed: FDE count dropped from 16,773 → 6,478 (-61%) without any source-level changes.
    2. --gc-sections was always doing its job for the actual code — I conflated "TU is pulled into the link" with "TU's code is in the binary". Only the eh_frame survived gc, and that's now stripped.

    Revised assessment of each reference

    # Reference Live code in binary? Worth fixing?
    1 CFastLED::add(audio) overloads No (192 bytes string pool) Low priority
    2 g_user_function = rgb_2_rgbw_exact YES (~434 bytes for 5 rgbw functions) Yes — only real binary win
    3 FileSystem::openVideo → Video::begin No Low priority
    4 Video::setTimeScale pimpl No Low priority
    5 http_parser → ChunkedReader::hasChunk No Low priority
    6 BLE → formatJsonResponse No Low priority
    7 fl.audio → apply_kernels No Low priority (depends on #1)
    8/9 string/sstream → audio::fft::Bins No Low priority

    Recommended action

    Scope this issue down to reference #2 only. The lazy-init refactor of g_user_function = rgb_2_rgbw_exact in src/fl/gfx/rgbw.cpp.hpp:116 is the only one that produces measurable binary savings (~434 bytes) on a default release build.

    The other eight references can be closed as "no-action — handled by --gc-sections for code, by #2423 for .eh_frame". They're stylistic improvements (cleaner module boundaries, reduced surprise pulls during debug builds) but they don't move the binary-size needle.

    If we ever decide that ESP32 panic backtrace-preserving builds need to be smaller too — i.e. builds where #2423's FL_NO_UNWIND is a no-op because the user wants backtraces — then the cross-TU fixes WOULD matter (each TU pulled in keeps its eh_frame). But that's a niche case; users who want both small binaries AND backtraces are a small intersection.

    Method notes for reproducibility

    # Baseline
    git checkout master && git pull
    bash compile esp32s3 --examples Blink
    ELF=.build/pio/esp32s3/.fbuild/build/esp32s3/release/firmware.elf
    xtensa-esp32s3-elf-readelf --debug-dump=frames "$ELF" | grep -c "FDE cie"
    xtensa-esp32s3-elf-nm --print-size --size-sort -C "$ELF" | grep -iE "audio|video|http|remote"
    xtensa-esp32s3-elf-size -A "$ELF" | grep -E "flash"
    
    # Treatment: #if 0 the four CFastLED::add/remove(audio...) overloads in
    #   src/FastLED.cpp.hpp:704-722 and their declarations in
    #   src/FastLED.h:798,815,830,858, then rebuild and re-measure.

    Working branch used: investigate/2424-cross-tu-refs (not for merge — pure verification).

  2. zackees commented on May 5, 2026

    @zackees
    MemberAuthor

    PR opened: #2426 — Singleton-based lazy init for rgb_2_rgbw user function

    Per the empirical findings above, the only reference from this issue's original list that touches live code in default release builds was g_user_function = rgb_2_rgbw_exact at static init. PR #2426 converts it to fl::Singleton<Rgb2RgbwUserState> lazy init.

    Honest empirical impact

    The Singleton refactor does NOT shrink the binary — measured +32 bytes on bash compile esp32s3 --examples Blink. The 5 rgb_2_rgbw_* algorithm functions remain in the binary because pixel_controller.h:613 calls the runtime-mode rgb_2_rgbw(rgbw_mode, ...) switch, which ODR-uses all 5 algorithm functions regardless of the static-init form.

    Why I'm pushing it anyway

    The Singleton form is a structural improvement independent of binary size:

    • No static init order dependency on rgb_2_rgbw_exact
    • Matches the Singleton pattern already used elsewhere in fl/
    • Cleaner override semantics (no special-case nullptr reset)

    What would actually shrink the binary for rgbw

    Per-mode template dispatch in pixel_controller.h::loadAndScaleRGBW so the compiler can statically eliminate unused branches of the rgb_2_rgbw(mode, ...) runtime switch. That's a much bigger refactor and out of scope for this issue.

    Status of the original 9 references

    # Reference Action
    1 CFastLED::add(audio) overloads No-action — --gc-sections already strips
    2 g_user_function = rgb_2_rgbw_exact PR #2426 (Singleton, +32 bytes structural)
    3 FileSystem::openVideo → Video::begin No-action — already stripped
    4 Video::setTimeScale pimpl No-action — already stripped
    5 http_parser → ChunkedReader::hasChunk No-action — already stripped
    6 BLE → formatJsonResponse No-action — already stripped (BLE driver isn't in NEOPIXEL link path)
    7 fl.audio → apply_kernels No-action — already stripped (depends on #1, both fully gc'd)
    8/9 string/sstream → audio::fft::Bins No-action — already stripped

    Recommendation

    After PR #2426 merges, this tracking issue can be closed. The --gc-sections + #2423 combination handles the 8 other references at zero cost. The remaining work is the deeper refactor of loadAndScaleRGBW for per-mode template dispatch, which is a much larger change worth filing as its own issue if anyone wants to pursue it.

  3. zackees commented on May 5, 2026

    @zackees
    MemberAuthor

    Closing — PR #2426 merged (commit 6d3b4d4). Empirical verification confirmed the other 8 cross-TU references identified in this issue are no-ops in default release builds (--gc-sections strips the code, #2423 strips the orphan .eh_frame). Any further binary-size work for the rgbw family would require per-mode template dispatch in pixel_controller.h::loadAndScaleRGBW — out of scope for this issue, file separately if pursued.

  4. zackees commented on May 9, 2026

    @zackees
    MemberAuthor

    Cross-link: #2428 is the complementary cleanup on the driver side. This issue (#2424) targeted unwanted cross-TU references in audio/net/video/fx/remote/third_party (~107 KB orphan eh_frame). #2428 targets the unconditional driver compilation + registration in platforms/esp/32/drivers/_build.cpp.hpp and channel_manager_esp32.cpp.hpp::initChannelDrivers() (the largest remaining bloat source after this issue's fixes landed). Combined recovery on the #2420 reproducer should exceed 400 KB.

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

    No labels
    No labels

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions