Skip to content

Meta: ESP32-S3 binary-size reduction — SUPERSEDED by #2773 (see comment for details) #2771

Closed as not planned

Description

@zackees

⚠️ Self-correction (2026-06-04): the first version of this issue counted
several rodata sections that the linker had already dropped (address == 0x00000000 in the map file). The mbedtls cert bundle, mesh strings,
huffTable, and PLM_AUDIO_SYNTHESIS_WINDOW are all already
tree-shaken
on the Blink build — they were never bloat in this binary.
Revised numbers below; see the correction
comment
for the methodology fix.

Summary

Meta-tracking issue for binary-size wins on the ESP32-S3 NEOPIXEL Blink
baseline (firmware.bin = 673,504 B, master 511730eb1c, PIO + IDF 5.4 +
xtensa-esp-elf-gcc 14.2.0). Each item below is verified against the live
binary (xtensa-esp32s3-elf-nm/-objdump on firmware.elf), with the
specific tree-shake mechanism that prevents -ffunction-sections +
--gc-sections from already handling it.

Source analysis: #2473 and the symbol audit posted there
(comment).


Why "add a macro" sometimes is the right answer

Reviewer asked: "I expected the linker to tree-shake these. Why aren't they
dropped?"
The honest answer per item:

  • Vtables defeat tree-shaking by design. A vtable is one rodata section
    pointing at every virtual method. The linker cannot drop rename() out of
    the vtable just because nobody calls it — the layout must be intact so
    ~VFSImpl can fire. One static reference to a class's vtable from
    FastLED's code pulls in every virtual method of that class plus
    everything those methods reference.
    Items 1.2 / 1.4 fall here.
  • Member initializers always run. class Foo { Bar1 a; Bar2 b; };
    always constructs both a and b, no matter what — the linker honors
    the C++ language. Item 1.4 specifically.
  • The linker drops whole functions, not parts of functions. A 5.7 KB
    Channel::showPixels that pulls in brightness + gamma + RGBW codepaths
    internally can only be split by us into multiple functions, then
    let the linker pick the right one. Items 2.1 / 2.2.
  • Live calls produce live data. Format strings inlined into
    FL_WARN(…) are live whenever the calls are live. The fix is to make
    the calls into no-ops in release builds (item 2.3), not anything in the
    linker.

Where the linker IS already doing the right thing (and my first version
incorrectly claimed it wasn't): mbedtls cert bundle, mesh strings,
huffTable, PLM_AUDIO_SYNTHESIS_WINDOW. Tree-shaken. Forget them.


Batch 1 — Low-hanging fruit (~26 KB total)

1.1 Eliminate C snprintf from libFastLED.a — ~11 KB

_svfprintf_r (11,118 B) is in the binary because libc_a-snprintf.o was
extracted to satisfy a snprintf reference from
libFastLED.a(platforms+.cpp.o). Concrete snprintf-call sites inside
FastLED:

  • src/platforms/esp/32/ota/ota_impl.cpp.hpp (7 sites) — hex encoding,
    auth string formatting. OTA functions are dead-stripped on this sketch
    but the .o file's relocations against snprintf survive archive
    extraction, which pulls libc_a-snprintf.o, which pulls
    _svfprintf_r.
  • src/third_party/TJpg_Decoder/driver.cpp.hpp
  • src/fl/audio/detector/key.cpp.hpp
  • src/fl/net/http/{stream_client,stream_transport,chunked_encoding}.cpp.hpp
  • src/fl/stl/asio/{ip/tcp,http/server}.cpp.hpp

Action: replace every C snprintf inside FastLED with fl::snprintf
(template-based, routes through fl::sstream, already implemented at
src/fl/stl/stdio.h:659). Drop the <cstdio>-injected C snprintf
declaration from FastLED headers. Add a clang-tidy / ci/lint_cpp/ rule
banning direct ::snprintf|::printf|::fprintf calls in src/.

Expected savings: ~11 KB (_svfprintf_r exits the binary). Headline
"why eliminate printf" — our fl::sstream-based formatter is also faster
than newlib for the integer-and-string cases FastLED actually uses.

Caveat: _vfprintf_r (another 11 KB) is ALSO in the binary but is pulled
by libesp_driver_gpio (ESP-IDF, not FastLED). We can't kill that from
here.


1.2 Gate <SD.h> include behind FASTLED_USE_SDCARD — ~14 KB

src/fl/system/file_system.cpp.hpp:20 auto-includes
platforms/fs_sdcard_arduino.hpp whenever both <SD.h> and <fs.h> exist:

#elif FL_HAS_INCLUDE(<SD.h>) && FL_HAS_INCLUDE(<fs.h>)
#include "platforms/fs_sdcard_arduino.hpp"

fs_sdcard_arduino.hpp unconditionally #include <SPI.h> and #include <SD.h>. PlatformIO LDF sees those, links libSD.a + libFS.a +
Arduino::VFSImpl. The chain why this can't be tree-shaken:

libFastLED.a(fl.system+.cpp.o)  ──refs──>  vtable for fs::File
                                            │
libSD.a(SD.cpp.o)               ──refs──>  vtable for VFSImpl
                                            │
libFS.a(vfs_api.cpp.o)          [defines vtable; pins all 12 VFSImpl methods]
                                            │
VFSFileImpl::VFSFileImpl()      ──calls──>  C snprintf  ──pulls──>  _svfprintf_r (11 KB)

The vtable is one rodata section that points at all 12 virtual methods;
the linker can't keep some and drop others. ~3 KB of VFSImpl/VFSFileImpl
code + the 11 KB printf engine = 14 KB in every ESP32 Blink, even though
nobody opens a file.

Action:

#elif defined(FASTLED_USE_SDCARD) && FL_HAS_INCLUDE(<SD.h>) && FL_HAS_INCLUDE(<fs.h>)
#include "platforms/fs_sdcard_arduino.hpp"
#define FASTLED_HAS_SDCARD 1

A deeper fix would be to refactor fl::FileSystem so it doesn't
statically reference fs::File (e.g. via type erasure) — but the
opt-in macro is correct AND minimal. Stacks with 1.1 (both kill the
same 11 KB printf engine via different chains; net savings is still
~14 KB after 1.1 lands, because the VFS code itself is 3 KB).


1.4 EspIO: pick one driver at construction — ~1 KB

src/platforms/esp/32/detail/io_esp_jtag_or_uart.hpp:51-93:

class EspIO {
    UartEsp32          mUart;              // <-- both members
    UsbSerialJtagEsp32 mUsbSerialJtag;     //     always constructed
    bool               mUseUsbSerialJtag;
public:
    void print(const char* str) {
        if (mUseUsbSerialJtag) { mUsbSerialJtag.write(str); }
        else                    { mUart.write(str); }
    }
};

Both mUart and mUsbSerialJtag are direct (non-pointer, non-variant)
members. The linker can't tree-shake one member out of a struct — the C++
language guarantees both constructors run. ~422 B (UartEsp32 ctor) +
~462 B (UsbSerialJtag ctor) + 184 B of paired singleton storage.

Action: replace with fl::variant<UartEsp32, UsbSerialJtagEsp32> or
polymorphic unique_ptr<IEspSerial>, chosen once at construction:

class EspIO {
    fl::variant<UartEsp32, UsbSerialJtagEsp32> mSerial;
public:
    void print(const char* s) {
        mSerial.visit([s](auto& dev){ dev.write(s); });
    }
};

LTO + dead-strip then keep only the actually-instantiated arm.

Expected savings: ~1 KB.


1.5 Lint rule banning direct ::snprintf / ::printf in src/ — 0 KB now, prevents 1.1 regression

After 1.1 lands, add a clang-tidy or ci/lint_cpp/ check that fails CI on
unqualified snprintf|sprintf|printf|fprintf|vfprintf|vsnprintf|vprintf
inside src/, excluding fl/stl/stdio.{h,hpp} and fl/stl/cstdio.* where
the fl::snprintf wrapper lives.


1.3 Move FastLED third_party/ codec rodata under opt-in — DROPPED

Originally I claimed fl::third_party::huffTable (8.5 KB) and
PLM_AUDIO_SYNTHESIS_WINDOW (2 KB) were leaking into the Blink rodata.
Re-checking: both are at section address 0x00000000 in the map file and
absent from xtensa-esp32s3-elf-nm output. The linker already
tree-shakes them.
No action needed.


Post-Batch-1 baseline projection

firmware.bin: 673,504 B → ~647 KB (–26 KB).


Batch 2 — Harder wins (~26–50 KB)

2.1 Tier Channel::showPixels for the no-brightness, no-gamma, no-XYMap path — ~3 KB

fl::Channel::showPixels<GRB, 1, 0xFFFFFFFF> is 5,690 B for a single
NEOPIXEL. Disassembly shows it pulls in ScaledPixelIteratorBrightness,
ScaledPixelIteratorRGB, ScaledPixelIteratorRGBW,
Gamma8::getOrCreate(float), XYMap::{getHeight,getWidth,mapToIndex},
PixelIteratorAny, and the Rgbww variant — even when the user never
calls setBrightness/setGamma/setCorrection and has no XYMap.

The linker can't help here because it drops whole functions, not
parts of functions. The fast path is hidden inside one big function.

Action: split into specialized templates so each path is a separate
linker unit:

template <typename ChipsetT>
void Channel::showPixels(PixelController<...>& pc) {
    if constexpr (has_no_runtime_scaling_v<ChipsetT>) {
        showPixels_passthrough(pc);   // ~500 B
    } else {
        showPixels_full(pc);          // ~5 KB
    }
}

--gc-sections + LTO then drop whichever variant isn't instantiated.

Expected savings: ~3 KB on the default Blink; proportional on more
complex sketches.

Risk: trait detection has to be conservative enough that
setBrightness() runtime calls still route to the full path.


2.2 Split ChannelEngineRMTImpl::createChannel static vs. dynamic — ~3 KB

Same shape as 2.1. createChannel (4,590 B) +
reconfigureForNetwork (2,160 B) implement the full hot-plug add/remove

  • WiFi-coexistence lifecycle. A sketch with one addLeds<> at static
    init never reconfigures, so the dynamic paths +
    NetworkDetector::isAnyNetworkActive() are dead weight.

Action: split into createChannel_static(...) and
createChannel_dynamic(...). A bool isStaticInit thread-local (false
after setup() returns) picks at the call site. The dynamic body is
only referenced from removeLeds()/late addLeds(), so it dead-strips
in static-only sketches.

Expected savings: ~3 KB.


2.3 FASTLED_LOG_VERBOSITY release knob — ~20–40 KB

The biggest single rodata contributor in the live binary is 57,902 B of
.str1.1 (merged string pool) in src/main.cpp.o
. This is the union of
every FL_WARN/FL_LOG format string inlined into the sketch TU from
FastLED headers. FL_WARN(X) expands to:

fl::println((fl::sstream() << fl::fastled_file_offset(__FILE__) << "(" <<
             int(__LINE__) << "): WARN: " << X).c_str())

Each callsite bakes the filename + line + user message into a literal.
This is NOT a tree-shake failure — the calls are live, so the strings
are live. The linker is doing the right thing.

Action: add a FASTLED_LOG_VERBOSITY knob:

  • 0 (release default for embedded): FL_WARN(X) → do {} while(0). Strings disappear, fl::sstream reference disappears, downstream _svfprintf_r reference may disappear too if all other callers also go.
  • 1 (debug, current behavior): full stream-style formatting.
  • 2 (verbose): plus stream << chains.

There is FASTLED_NO_LOG today but it's all-or-nothing and not the
right shape for a release-mode embedded option.

Expected savings: ~20–40 KB. Hard to pin down without measuring,
because the 57 KB string pool isn't 100% from FL_WARN — some is from
ESP-IDF format-passthrough strings. Probably 30–40 KB from FastLED's
share.


2.4 Upstream Arduino-ESP32: drop WPA/mesh when unused — DROPPED

Originally claimed ~85 KB savings from getting Arduino-ESP32 to elide
WPA Supplicant + the mbedtls cert bundle when WiFi isn't initialized.
Verification: the cert bundle and mesh strings are already tree-shaken
on the Blink build
. No win available from upstream on this specific
sketch.

(The point may still apply to sketches that touch some WiFi-adjacent
type without calling WiFi.begin() — but on plain NEOPIXEL Blink, the
linker has done its job.)


2.5 RMT memory planner: compile-time fixed allocation for single strips — ~3-4 KB

fl::RmtMemoryManager::allocateTx (2,708 B) +
calculateMemoryBlocks (826 B) + freeDMA (480 B) implement a runtime
memory-block planner for arbitrary channel counts and lengths. A
single-strip Blink only needs one fixed RMT memory block — the planner
is overkill.

Action: trait-detect at template-instantiation time when addLeds<>
is called exactly once with a known length, and skip the planner via
compile-time-fixed allocation. Same if constexpr shape as 2.1.

Expected savings: ~3-4 KB.


Tracking matrix (revised)

Item Batch Est. savings Mechanism Status
1.1 Eliminate C printf-family in libFastLED.a 1 ~11 KB snprintf → fl::snprintf not started
1.2 Gate <SD.h> behind FASTLED_USE_SDCARD 1 ~14 KB vtable-chain prevents tree-shake not started
1.3 codec rodata gate — 0 KB already tree-shaken dropped
1.4 EspIO variant-based driver selection 1 ~1 KB member init defeats tree-shake not started
1.5 Lint rule banning direct ::snprintf/::printf 1 regression guard — not started
2.1 Tier Channel::showPixels fast path 2 ~3 KB function not separable not started
2.2 Split RMT createChannel static vs. dynamic 2 ~3 KB function not separable not started
2.3 FASTLED_LOG_VERBOSITY release knob 2 ~20–40 KB live calls = live strings not started
2.4 Upstream WPA/mesh elision — 0 KB on Blink already tree-shaken dropped
2.5 RMT planner compile-time fixed alloc 2 ~3-4 KB function not separable not started

Revised Batch 1 total: ~26 KB → 673 KB → ~647 KB.
Revised Batch 2 total: ~26–50 KB (mostly the FASTLED_LOG_VERBOSITY win).

Realistic post-everything baseline: ~595–620 KB on ESP32-S3 NEOPIXEL
Blink. The 250–270 KB gap to the 3.10.3 baseline (344 KB) is the new
ChannelManager/RMT architecture introduced for #2420 and is structural —
items 2.1/2.2/2.5 chip into it but won't close it without a deeper
redesign.

Related issues

Activity

  1. zackees commented on Jun 5, 2026

    @zackees
    MemberAuthor

    ⚠️ Self-correction: original post had four false positives

    A reviewer caught that the map-file analysis I used to build this issue didn't filter for address != 0x00000000 — i.e. sections listed in the map but already dropped by --gc-sections were being counted as live. Re-running with the correct filter shows the linker is doing better than I credited:

    Item I claimed was in the binary Reality
    mbedtls X.509 CA bundle (~68 KB) ❌ Already tree-shaken — section at 0x00000000
    libmesh.a strings (~17 KB) ❌ Already tree-shaken
    fl::third_party::huffTable (8.5 KB) ❌ Already tree-shaken — not in nm output
    PLM_AUDIO_SYNTHESIS_WINDOW (2 KB) ❌ Already tree-shaken

    That removes ~95 KB of phantom savings from the totals and invalidates Batch 1 item 1.3 entirely. I'll edit the body next.

    What IS actually in the binary, and the real tree-shake mechanism for each

    1. Arduino VFS/FS code (~3 KB) + _svfprintf_r (11 KB) — vtable chain, not a printf-detection failure. Map evidence:

      libFastLED.a(fl.system+.cpp.o) ──refs──> vtable for fs::File
                                                │
      libSD.a(SD.cpp.o)              ──refs──> vtable for VFSImpl
                                                │
      libFS.a(vfs_api.cpp.o)         [defines vtable; holds all 12 VFSImpl methods alive]
                                                │
      VFSFileImpl::VFSFileImpl()     ──calls──> C snprintf ──pulls──> _svfprintf_r (11 KB)
      

      -ffunction-sections + --gc-sections cannot break this: a vtable is one rodata section pointing at every virtual method. The linker can't drop rename() out of the vtable just because nobody calls it — the layout must be intact for ~VFSImpl to fire correctly. One static reference to fs::File's vtable from FastLED pulls in 14 KB of otherwise-dead code. Item 1.2's FASTLED_USE_SDCARD gate works because it prevents the reference from being emitted in the first place; the deeper fix would be to remove the static fs::File reference from FastLED's default path.

    2. EspIO with both UartEsp32 mUart; and UsbSerialJtagEsp32 mJtag; as direct members (~1 KB) — the linker cannot tree-shake one struct member out of a class. The C++ language guarantees both constructors run when EspIO is constructed; --gc-sections honors that. Item 1.4's variant rewrite is a proper fix (not a macro).

    3. Channel::showPixels 5.7 KB + createChannel 4.6 KB — not tree-shake failures. The linker drops whole functions, not parts of functions. Item 2.1 / 2.2 (split into specialized templates + if constexpr dispatch) gives the linker separable units to drop. The compiler/linker cannot do this on its own.

    4. 57 KB .str1.1 merged string pool in main.cpp.o — not a tree-shake failure either. These are FL_WARN format strings inlined into the sketch TU from FastLED headers; they're live because the call sites are live. The linker is correct. Item 2.3 (FASTLED_LOG_VERBOSITY release knob to no-op FL_WARN) is the right shape.

    Item 1.1 (printf elimination) is still valid

    _svfprintf_r (11 KB) really is in the binary and really is pulled by libFastLED.a(platforms+.cpp.o) referencing C snprintf. Replacing FastLED-internal C snprintf calls with fl::snprintf (which goes through fl::sstream and doesn't need newlib's printf engine) still saves ~22 KB if no other live path in the binary references C snprintf. I need to verify the "no other live path" condition before I claim the full 22 KB, but the direction is right.

    Updated savings estimate

    Item Was claimed Honest estimate Mechanism
    1.1 Eliminate C printf-family in libFastLED.a ~22 KB ~11 KB (only _svfprintf_r for sure; _svfiprintf_r is from libc internals, not us) Real
    1.2 Gate <SD.h> behind FASTLED_USE_SDCARD ~14 KB ~14 KB Real — vtable chain
    1.3 Move codec rodata under opt-in ~10.5 KB 0 KB — already tree-shaken DROP THIS ITEM
    1.4 EspIO variant-based selection ~1 KB ~1 KB Real — member init
    1.5 Lint rule regression guard regression guard Unchanged
    2.1 Tier Channel::showPixels ~3 KB ~3 KB Real — function size
    2.2 Split RMT createChannel ~3 KB ~3 KB Real — function size
    2.3 FASTLED_LOG_VERBOSITY release knob 10–20 KB likely 20–40 KB (the 57 KB string pool is mostly FL_WARN) Real — strips live calls
    2.4 Upstream Arduino-ESP32 WPA/mesh elision ~85 KB 0 KB on Blink (already tree-shaken on this sketch) — value only appears for sketches that link some WiFi-adjacent code without using WiFi DROP this from Blink projection
    2.5 RMT planner compile-time fixed alloc 3–4 KB 3–4 KB Real

    Revised Batch 1 total: ~26 KB (was 48 KB).
    Revised Batch 2 total: ~26–50 KB (was 20–90 KB).

    I'll edit the issue body to reflect this so future readers don't see the wrong numbers as the headline.

  2. changed the title [-]Meta: ESP32-S3 binary-size reduction — Batch 1 low-hanging fruit (~48 KB) + Batch 2 architectural (~20-90 KB)[/-] [+]Meta: ESP32-S3 binary-size reduction — Batch 1 ~26 KB + Batch 2 ~26-50 KB (corrected)[/+] on Jun 5, 2026
  3. zackees commented on Jun 5, 2026

    @zackees
    MemberAuthor

    ⚠️ Superseded by #2773

    This issue's original numbers had ~95 KB of phantom savings because the map-file audit didn't filter sections placed at address == 0x00000000 (= dropped by --gc-sections). The correction comment walked the headline numbers back, but the issue body, title, and tracking matrix here are still confusing for first-time readers.

    Use #2773 as the canonical source going forward. It's the same proposal with:

    Keeping this issue open for history so the correction chain is discoverable; subsequent PRs should reference #2773.

  4. changed the title [-]Meta: ESP32-S3 binary-size reduction — Batch 1 ~26 KB + Batch 2 ~26-50 KB (corrected)[/-] [+]Meta: ESP32-S3 binary-size reduction — SUPERSEDED by #2773 (see comment for details)[/+] on Jun 5, 2026
  5. zackees commented on Jun 5, 2026

    @zackees
    MemberAuthor

    Closing as superseded by #2773 (per the title and self-correction note). All remaining size-reduction work tracked there.

  6. moved this from Triage to Done in FastLED Trackeron Jun 5, 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

    No labels
    No labels

    Type

    No type

    Projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions