Skip to content

research: tree-shake unused Channels encoders like unused drivers #3947

Open

Description

@zackees

Context

PR #3911 added the TM1812 RGBWW frame encoder to the Channels API. The ESP32-S3 Blink bloat gate then measured 340,768 B -> 341,051 B (+283 B) even though Blink does not select TM1812; #3944 / #3945 accepted that measured feature cost into the baseline.

This is not caused merely by including tm1812.h. The encoder is a template, so including its definition is normally code-size-neutral until something instantiates it. The retention edge is the live runtime dispatch in src/fl/channels/channel.cpp.hpp:

switch (clockless->encoder) {
    case ClocklessEncoder::CLOCKLESS_ENCODER_WS2812:
        pixelIterator.writeWS2812(&data);
        break;
    case ClocklessEncoder::CLOCKLESS_ENCODER_TM1812_RGBWW:
        pixelIterator.writeTM1812RGBWW(&data);
        break;
    // UCS7604 cases...
}

Every direct call is statically reachable from Channel::showPixels(), so the compiler/linker must retain the corresponding writer body even when the sketch's configuration can only produce WS2812. The same shape exists in the SPI chipset switch.

We already solved the analogous driver problem in #2428: compile-time paths ODR-use only the selected BusTraits<Bus::X> specialization, while enableAllDrivers() is the explicit runtime-flexible path that intentionally retains all drivers. Encoders currently lose their compile-time identity early:

  • makeClockless<TIMING>() reduces TIMING to a runtime ClocklessEncoder enum.
  • FastLED.addLeds<SPI_CHIPSET, ...>() reduces the template argument to a runtime SpiEncoder enum/config.
  • TypedChannel<Bus, Chipset> preserves the bus and chipset family, but returns the same non-template Channel; it does not preserve the concrete encoder.
  • Channel::showPixels() therefore has to reference every enabled writer from one central switch.

Existing tactical gates prove the opportunity but do not scale:

This issue is a research proposal only. Do not implement or merge an encoder-dispatch refactor under this issue yet. The immediate deliverable is a measured design recommendation and a set of implementation-ready follow-up issues.

Proposal

Research a linker-elidable encoder binding architecture modeled on BusTraits.

The leading candidate is a small type-erased encoder thunk stored in the erased chipset configuration, with compile-time trait specializations providing the thunk:

using EncodeFn = void (*)(PixelIterator&, fl::vector_psram<u8>&,
                          const EncoderContext&);

template<ClocklessEncoder E>
struct ClocklessEncoderTraits;  // primary template intentionally undefined

template<>
struct ClocklessEncoderTraits<ClocklessEncoder::CLOCKLESS_ENCODER_TM1812_RGBWW> {
    static void encode(PixelIterator&, fl::vector_psram<u8>&,
                       const EncoderContext&);
};

Conceptually:

  1. makeClockless<TIMING>() binds ClocklessEncoderTraits<encoder_for<TIMING>()>::encode directly. The selected thunk is the only encoder ODR-used by that construction path.
  2. Compile-time SPI addLeds<CHIPSET, ...>() similarly binds a SpiEncoderTraits<CHIPSET> thunk.
  3. ClocklessChipset / SpiChipsetConfig retain their existing enum values for equality, diagnostics, and runtime introspection, while also carrying an encoder binding or another compact indirection chosen by the research.
  4. Channel::showPixels() performs one indirect encoder call instead of directly naming every writer in central switches.
  5. Truly runtime-selected enums use a separately linked resolver/registry (enableEncoders<...>() / enableAllEncoders() or equivalent). Like enableAllDrivers(), referencing that runtime entry point intentionally retains the selected set or the full encoder set.
  6. Missing bindings must fail clearly at creation/registration time. The current disable flags can silently emit nothing when a disabled chipset is selected; the structural design should not preserve that failure mode.

The exact API names above are illustrative, not decided.

Strategies to evaluate

A. Per-encoder disable macros

Add gates such as a TM1812-specific disable macro around each switch arm.

  • Advantage: smallest and lowest-risk tactical change; likely recovers the known 283 B immediately.
  • Disadvantages: opt-out rather than automatic, macro count grows with every encoder, invalid combinations can silently drop output, and the default binary keeps growing.
  • Research disposition: retain as a short-term escape hatch only if the structural work proves too risky; do not make it the target architecture.

B. Out-of-line writer functions only

Move each writer behind a noinline/out-of-line function and keep the central switch.

C. Encoder traits + bound function pointer/thunk (leading candidate)

Bind a concrete encoder at compile time, erase only its callable shape into Channel, and isolate all-encoder lookup in an opt-in runtime TU.

  • Advantages: mirrors the proven BusTraits model; preserves one runtime Channel type; avoids heap allocation and per-frame registry lookup; allows --gc-sections to drop unreferenced thunks.
  • Costs/risks: one pointer or compact binding per channel/config unless it can be folded into existing storage; equality/copy semantics need definition; UCS7604 needs more context than TM1812/WS2812; C++11 compatibility must be preserved.
  • Research disposition: prototype and measure first.

D. Template Channel on concrete encoder

Carry the encoder type all the way through a Channel<Bus, Encoder> specialization and call it statically.

  • Advantages: maximal compiler visibility and potentially no function-pointer field/call.
  • Costs/risks: large API/ABI blast radius, duplicates more of Channel::showPixels() per encoder, complicates the existing CLEDController/ChannelPtr polymorphic surface, and can exchange retained encoder bloat for duplicated channel bloat.
  • Research disposition: measure as an upper-bound experiment, not the default recommendation.

E. Driver-owned virtual encoder dispatch

Move encoder selection onto IChannelDriver, as one option in #2981.

  • Advantage: one virtual call can split the current monolithic symbol.
  • Risks: encoding is a chipset concern shared across buses, so placing it on every driver creates a driver x encoder cross-product or forces each live driver to reference all encoders it supports. It may improve symbol layout without solving selection-based tree shaking.
  • Research disposition: evaluate only if a driver can receive an already-bound encoder thunk; do not make drivers own the encoder inventory.

F. Weak symbols/linker-set discovery

Use weak references, linker sections, or generated tables.

  • Advantage: can avoid a stored pointer or explicit registry API.
  • Risks: toolchain-specific behavior across AVR, Xtensa/RISC-V ESP32, ARM, WASM, and host builds; harder diagnostics and tests.
  • Research disposition: reject unless the portable C++11 approaches fail measured requirements.

Research plan

  1. Produce a controlled encoder-retention matrix using the existing bloat workflow and link maps:
    • WS2812-only Blink
    • TM1812 RGBWW only
    • UCS7604 only
    • one representative SPI chipset
    • two-encoder mixed build
      Record total flash and the retained write* / encode* symbols for each.
  2. Verify the current RED condition: a WS2812-only build grows or retains TM1812/UCS7604/SPI writer code solely because the central dispatch references it.
  3. Prototype strategy C on a research branch without opening an implementation PR. Compare:
    • total flash
    • Channel::showPixels() symbol size
    • per-channel RAM/config size
    • encode throughput
    • map evidence showing only selected encoder thunks are retained
  4. Prototype strategy D only far enough to establish whether whole-Channel specialization causes code duplication.
  5. Test both API modes:
    • compile-time makeClockless<TIMING>() / addLeds<CHIPSET>(): retain only selected encoder(s)
    • runtime enum/config selection: explicitly retain the requested registry set or all encoders, with a documented size warning comparable to runtime driver selection
  6. Produce a short design note with the measurement table, recommended ABI/API shape, migration plan, and separately scoped implementation issues.

Acceptance criteria

This research issue is complete when:

  • Before/after link-map and flash measurements exist for the five-build matrix above on ESP32-S3.
  • At least one small secondary target (AVR or ARM) is measured to catch pointer/config overhead that ESP32 may hide.
  • The report distinguishes template-header parsing from actual code generation and identifies every strong reference retaining an unused encoder.
  • Strategy C has a non-merged prototype demonstrating whether a WS2812-only compile-time build can omit TM1812, UCS7604, and SPI encoder bodies.
  • Runtime-selected configuration behavior is specified, including how users explicitly request multiple/all encoders and what diagnostic occurs for an unavailable encoder.
  • C++11, no-heap, no-exceptions, RGB/RGBW/RGBWW, color-order, gamma, XYMap, and mixed-encoder requirements are covered.
  • The recommendation quantifies flash savings, any RAM cost per channel, and encode-time overhead.
  • No production implementation is merged from this research issue; follow-up implementation work is split into independently reviewable issues.
  • Every future implementation issue requires RED -> GREEN evidence: a focused map/bloat repro that initially retains an unused encoder, then proves that encoder absent after the change, plus functional encoder tests remaining green.

Decisions

  • Priority: P2 research. The regression is measurable and compounds with every new runtime encoder, but current functionality is correct and test: accept TM1812 encoder flash cost #3945 restored the hard size gate.
  • Scope: Channels byte/frame encoders, both clockless and SPI. The same central-dispatch retention mechanism affects both families, so solving only TM1812 would repeat the problem later.
  • Preferred direction: trait-bound thunk plus explicit runtime registry. It most closely matches the already-shipped driver elision model while preserving the non-template runtime Channel object.
  • No implementation yet. This issue authorizes measurement, prototypes, and design documentation only; production code changes require follow-up issues after the recommendation is reviewed.
  • RMT hardware sub-encoders are separate. ESP-IDF bytes/copy encoders are implementation details of the selected RMT driver; per-chipset RMT5 instantiation/dedup remains tracked by Meta: ESP32-S3 binary-size reduction — Batch 3 (successor to #2773) #2856 item 3.4 and should not be conflated with the Channels pixel-writer retention shown by TM1812.
  • Do not rely on LTO to infer runtime values. The design should establish structural reachability boundaries that work with the repository's supported toolchains and --gc-sections model.

Open questions

  • Can the bound thunk reuse existing enum/config storage without increasing ClocklessChipset, SpiChipsetConfig, or Channel RAM footprint?
  • Should dynamic mode expose enableEncoders<...>(), infer the needed registry from config construction, or mirror enableAllDrivers() exactly?
  • Can clockless and SPI writers share one erased callable signature without pulling unused RGBW/RGBWW context into the common WS2812 path?
  • Does one indirect call per frame remain effectively free on the smallest supported AVR targets, or should those keep a specialized static path?

Related issues

Activity

  1. zackees commented on Aug 20, 2026

    @zackees
    MemberAuthor

    Deferred after current-master triage.

    This issue is intentionally not a bounded production fix: its own acceptance criteria require a five-build ESP32-S3 link-map/flash matrix, a second-target measurement, non-merged strategy C and D prototypes, runtime-registry/API/ABI design, and separately filed implementation issues. It also explicitly forbids merging the production refactor under this issue. The central strong references remain present in src/fl/channels/channel.cpp.hpp, and the closely related dispatch-architecture work in #2981 is already deferred pending benchmark evidence.

    Current known evidence remains useful but insufficient for closeout: TM1812 added 283 B to a WS2812-only Blink path (#3944/#3945), the current release gate is 341,051 B, and the SPI/UCS7604 opt-out gates demonstrate larger possible savings. None of that supplies the requested mixed-encoder maps, RAM/throughput costs, secondary-target result, or runtime-selection contract.

    Restart when one owner can provide a reproducible same-SHA measurement harness that emits the five requested link maps plus one AVR/ARM result. At that point, prototype the trait-bound thunk on a research branch, record flash/RAM/throughput and retained-symbol evidence, decide the runtime registry contract, and split the recommendation into independently reviewable implementation issues. Remove deferred only when that research package exists.

  2. added
    deferred
    on Aug 20, 2026
  3. added a commit that references this issue on Sep 3, 2026
  4. zackees commented on Oct 2, 2026

    @zackees
    MemberAuthor

    LPC845 AutoResearch flash accounting (arm-none-eabi-gcc 15.2, LTO, 64 KB part), from bash compile lpc845 --examples AutoResearch map files:

    Build Flash inputs Result
    7ff7c4aad0^ (direct-driver controllers) 67,176 B links
    7ff7c4aad0 (SlimBridgeController) 85,799 B FLASH overflowed by 16448 bytes
    this PR, RGB/RGBW only 63.21 KB links
    this PR + getRgbww() 63.29 KB links (+80 B)

    Where the +18.6 KB went with SlimBridge:

    • fl.channels +3.7 KB and fl.stl +3.6 KB: ChannelManager registration and registry.
    • About 8 KB from the printf formatter: fl::printf_detail plus libgcc double soft-float (adddf3, subdf3, muldf3, divdf3, ...), pulled in by printf-style FL_WARN/FL_DBG in ChannelManager::addDriverSlow that registration makes reachable.
    • main +1 KB.

    PixelIterator costs about 1.7 KB of the image either way: load/scale bindings, the RGB/RGBWW range iterators, and the rgb_2_rgbw* converters. About 1.1 KB of that is RGBW/RGBWW code, already linked because writeWS2812 selects RGB/RGBW/RGBWW at runtime and setRgbw()/setRgbww() are runtime APIs. Passing getRgbww() through costs 80 B, so RGBWW is restored here.

    The #3947 encoder switch in Channel::showPixels() is not on the LPC path: these controllers and SlimBridge both call writeWS2812 directly.

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

    deferred

    Type

    No type

    Projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions