Skip to content

feat(channels): compile-time Bus binding via templated ChannelConfig (eliminates Channel API binary bloat) #2428

Closed

Description

@zackees

Summary

Introduce a strongly-typed fl::Bus enum and a ChannelConfig<Chipset> template so each Channel is bound to its driver at compile time. This:

  1. Eliminates the Channel API binary bloat from [Tracking] ESP32-S3 timing regression + binary bloat from Channel API (from #2420) #2421 — drivers only link when their Bus is named.
  2. Closes FastLED Channels API #2167 (Channel::create<EngineType>(config) becomes a real template).
  3. Makes bus/chipset mismatches compile errors instead of runtime warnings.

Problem

Today, every ESP32 driver (RMT, PARLIO, SPI, I2S, LCD_RGB, LCD_SPI, BLE, UART, …) is unconditionally compiled and registered with ChannelManager via initChannelDrivers() in src/platforms/esp/32/drivers/channel_manager_esp32.cpp.hpp. Driver selection happens at runtime through IChannelDriver::canHandle() virtual dispatch, so --gc-sections cannot strip unused drivers. A NEOPIXEL-only sketch links every driver and grew from 344 KB → 783 KB between 3.10.3 and master (see #2420 reproducer).

Additionally, the new Channel API in #2167 has two papercuts:

  • Channel::create<fl::ChannelEngineSpi>(config) doesn't compile — create() isn't a template.
  • The string-based mAffinity = "RMT" is typo-prone and heap-allocates.

Proposed API

Single source of truth: fl::Bus enum

namespace fl {
enum class Bus : fl::u8 {
    AUTO,         // sentinel — pick DefaultBus<Chipset>
    RMT,
    PARLIO,
    SPI,
    I2S,          // LCD_CAM clockless on S3
    LCD_RGB,
    LCD_SPI,
    OBJECT_FLED,  // Teensy
    STUB,
};

// Per-platform default per chipset family
template<typename Chipset> struct DefaultBus;
template<> struct DefaultBus<ClocklessChipset> {
    static constexpr Bus value = /* ESP32-P4: PARLIO, S3/dev: RMT, Teensy: OBJECT_FLED, ... */;
};
template<> struct DefaultBus<SpiChipsetConfig> {
    static constexpr Bus value = /* ESP32: SPI, S3: LCD_SPI, ... */;
};
} // namespace fl

Templated ChannelConfig<Chipset> carries the chipset family as a type

template<typename Chipset>   // ClocklessChipset or SpiChipsetConfig
struct ChannelConfig { /* same fields, no ChipsetVariant erasure */ };

BusTraits<B> exposes capability

template<fl::Bus B> struct BusTraits;  // primary undefined → unsupported = compile error

template<> struct BusTraits<fl::Bus::PARLIO> {
    using Driver = ChannelDriverPARLIO;
    static Driver& instance();   // Meyers singleton — naming this is what links the driver
    template<typename Chipset>
    static constexpr bool supports = fl::is_same_v<Chipset, ClocklessChipset>;
};

template<> struct BusTraits<fl::Bus::SPI> {
    using Driver = ChannelEngineSpi;
    static Driver& instance();
    template<typename Chipset>
    static constexpr bool supports = fl::is_same_v<Chipset, SpiChipsetConfig>;
};
// ...one specialization per driver, lives next to the driver header

Channel<B, Chipset> is templated; add() and create() deduce Chipset from the config

template<fl::Bus B, typename Chipset>
class Channel : public CPixelLEDController<RGB> {
public:
    static fl::shared_ptr<Channel<B, Chipset>> create(const ChannelConfig<Chipset>& cfg);
protected:
    void showPixels(...) override {
        BusTraits<B>::instance().enqueue(mChannelData);   // direct, no virtual, no manager
    }
};

template<auto B = fl::Bus::AUTO, typename Chipset>
auto CFastLED::add(const ChannelConfig<Chipset>& cfg) {
    constexpr fl::Bus actual = (B == fl::Bus::AUTO) ? DefaultBus<Chipset>::value : B;
    static_assert(BusTraits<actual>::template supports<Chipset>,
                  "This Bus does not support this chipset family (clockless vs SPI)");
    auto ch = Channel<actual, Chipset>::create(cfg);
    ch->addToDrawList();
    return ch;
}

Minimal usage

#include "FastLED.h"

CRGB leds[60];

void setup() {
    fl::ChannelConfig cfg{fl::ClocklessChipset(4, fl::makeTimingConfig<fl::TIMING_WS2812_800KHZ>()),
                          fl::span<CRGB>(leds, 60), GRB};

    FastLED.add(cfg);                          // platform default clockless bus
    FastLED.add<fl::Bus::RMT>(cfg);            // OK — RMT supports clockless
    FastLED.add<fl::Bus::SPI>(cfg);            // ❌ compile error: SPI bus, clockless chipset
}

void loop() { FastLED.show(); }

Parallel multi-channel

FastLED.add<fl::Bus::PARLIO>({cfg_strip1, cfg_strip2, ..., cfg_strip16});
FastLED.add<fl::Bus::SPI>(cfg_apa102);
// → only PARLIO + SPI driver TUs link

Runtime-flexible mode (opt-in)

For users who genuinely need runtime driver selection (third-party drivers, dynamic switching, MoonLight-style flexibility from #2167), explicit enrollment forces linking AND registers with ChannelManager:

void setup() {
    FastLED.enableDrivers<fl::Bus::RMT, fl::Bus::PARLIO, fl::Bus::SPI>();
    FastLED.add(cfg);                                 // manager picks best of {RMT, PARLIO, SPI}
    cfg.options.mAffinity = fl::Bus::PARLIO;          // mAffinity is now fl::Bus, not fl::string
    FastLED.add(cfg);                                 // explicit runtime override
    FastLED.setExclusiveDriver(fl::Bus::RMT);         // disable others
}

// Convenience for prototyping / 3.10.3-style behavior:
FastLED.enableAllDrivers();
// or:
#include "fl/channels/all_drivers.h"

Implementation:

template<fl::Bus... Buses>
void CFastLED::enableDrivers() {
    (BusTraits<Buses>::registerWithManager(), ...);   // C++17 fold
    // Each call ODR-uses BusTraits<B>::instance() (links the TU) AND
    // registers with ChannelManager for runtime selection.
}

Deletions / simplifications

Removed (default path) Replaced by
Bus::AUTO runtime dispatch through ChannelManager DefaultBus<Chipset>::value compile-time
ChannelOptions::mAffinity as fl::string fl::Bus enum (1 byte, no heap, type-safe)
IChannelDriver virtual dispatch on hot path Direct BusTraits<B>::instance().enqueue()
ChannelManager::addDriver / selectDriverForChannel (eager) Lazy via enableDrivers<...>() opt-in
initChannelDrivers() + addParlioIfPossible / addRmtIfPossible / etc. Nothing — driver TUs link when their BusTraits<B>::instance() is named
setExclusiveDriver / setDriverEnabled / setDriverPriority Available only in registry mode (still works, takes fl::Bus not string)
IChannelDriver::getName() / getBus() virtual Encoded in the type (Channel<B, Chipset>)
EngineEvents::onBeginFrame waitForReady() floor (the vTaskDelay(1) from #2421) Gone in default path — manager isn't on the call chain
src/platforms/esp/32/drivers/_build.cpp.hpp aggregator Per-driver _build.cpp.hpp files only included via header chain

Compile-time enforcement examples

// Mismatch: compile error, not runtime warning
ChannelConfig cfg_spi{SpiChipsetConfig(23, 18, apa102), leds};
FastLED.add<fl::Bus::PARLIO>(cfg_spi);
// ❌ static_assert: "This Bus does not support this chipset family"

// Typo: compile error, not silent fallthrough
FastLED.add<fl::Bus::RTM>(cfg);
// ❌ no member named 'RTM' in 'fl::Bus'

// Naming an undefined driver on this platform: compile error
FastLED.add<fl::Bus::PARLIO>(cfg);   // on ESP32-dev (no PARLIO peripheral)
// ❌ implicit instantiation of undefined template 'BusTraits<Bus::PARLIO>'

Migration path

  1. Existing addLeds<> sketches: zero source change. addLeds<WS2812, 4, GRB>(leds, n) keeps its current signature; internally it instantiates Channel<DefaultBus<ClocklessChipset>::value, ClocklessChipset>. NEOPIXEL-only sketches link one driver.
  2. Existing Channel::create(cfg) callers: source-compatible — create() defaults to Bus::AUTO, which resolves to the platform default for the chipset.
  3. Existing affinity-string callers (README examples in src/fl/channels/README.md lines 333–345): one-line s/"RMT"/fl::Bus::RMT/. Old string form can be kept as a deprecated overload for one release.
  4. MoonLight integration (FastLED Channels API #2167): gets its requested template form: Channel<fl::Bus::SPI>::create(cfg) or FastLED.add<fl::Bus::SPI>(cfg).

Expected size impact

For the #2420 reproducer (NEOPIXEL on ESP32-S3): ~783 KB → ~344 KB (back to 3.10.3 baseline).

Combined with #2424's source-level cleanup of cross-TU references, total recovery exceeds 400 KB on that build.

Implementation phasing

  1. Phase 1 — Add fl::Bus enum, BusTraits<B> skeleton, DefaultBus<Chipset>. No behavior change yet (parallel API alongside existing).
  2. Phase 2 — Templatize ChannelConfig<Chipset> and Channel<B, Chipset>. Add FastLED.add<>() template. Existing Channel::create(ChannelConfig) becomes a deprecated wrapper around Channel<AUTO, ClocklessChipset>::create().
  3. Phase 3 — Implement enableDrivers<>() and enableAllDrivers(). Make ChannelManager/IChannelDriver opt-in via FASTLED_ENABLE_DRIVER_REGISTRY.
  4. Phase 4 — Drop the _build.cpp.hpp aggregator default; gate behind FASTLED_REGISTER_ALL_DRIVERS. Remove eager initChannelDrivers() registration. Convert mAffinity from fl::string to fl::Bus.
  5. Phase 5 — Measure binary size on [Bug] Compounded timing inaccuracy on master compared to 3.10.3 #2420 reproducer + Teensy 3.0/LC (Teensy 3.0 / LC link-time RAM overflow (.dmabuffers / .bss) across all examples #2406). Validate timing on the [Tracking] ESP32-S3 timing regression + binary bloat from Channel API (from #2420) #2421 reproducer (manager-side vTaskDelay(1) floor should be gone in default path).

Related

Activity

  1. added
    type: feature
    area: core
    on May 9, 2026
  2. zackees commented on May 10, 2026

    @zackees
    MemberAuthor

    Status check per @zackees:

    Done:

    Outstanding:

    Phase 5 is the highest-value remaining work. Phase 3b is API ergonomics polish that can ship later.

  3. zackees commented on May 24, 2026

    @zackees
    MemberAuthor

    Closing as completed. Audit of the codebase against each phase below.

    Phase 1 — fl::Bus enum + BusTraits<B> foundation ✅

    • feat(channels): add fl::Bus enum + BusTraits foundation (Phase 1 of #2428) #2429 merged.
    • src/fl/channels/bus.h:44 defines enum class Bus : fl::u8 { AUTO, RMT, PARLIO, SPI, I2S, LCD_RGB, LCD_SPI, OBJECT_FLED, STUB, ... }.
    • src/fl/channels/bus_traits.h provides BusTraits<B> + BusSupports<B, Chipset>.
    • DefaultBus<Chipset> specializations per platform exist in src/fl/channels/bus.h (lines 82, 86, 97, 101, 111, 115, 122 — one per platform/chipset pair).

    Phase 2 — Per-driver BusTraits<B> specializations ✅

    Phase 3a — IChannel ABC base ✅

    Phase 3b — Templated channel + config ✅ (with API walkback)

    Phase 4 — enableDrivers<Bus...>() opt-in registry ✅

    Phase 5 — Drop unconditional driver aggregator + retarget legacy addLeds<> ✅

    Deletions / simplifications from the issue body

    Removed Status
    Bus::AUTO runtime dispatch through ChannelManager Replaced by DefaultBus<Chipset>::value ✅
    ChannelOptions::mAffinity as fl::string Removed (#2461); now typed mBus : fl::Bus ✅
    IChannelDriver virtual dispatch on hot path BusTraits<B>::instance() direct call ✅
    Eager ChannelManager::addDriver / selectDriverForChannel Lazy via enableDrivers<...>() opt-in ✅
    initChannelDrivers() + addParlioIfPossible etc. Driver TUs link only when BusTraits<B>::instancePtr() is named ✅
    setExclusiveDriver string form Now takes fl::Bus (#2472) ✅
    IChannelDriver::getName() / getBus() virtual Encoded in the type ✅
    EngineEvents::onBeginFrame waitForReady() floor (vTaskDelay(1)) Removed in default path (#2503) ✅
    _build.cpp.hpp aggregator Gated per-driver; only platform-default drivers compile unconditionally ✅

    Sub-issues closed by this work

    Still outstanding (separate from #2428)

    Minor doc loose end

    src/fl/channels/channel.h:47 still has the comment "after Channel<Bus, Chipset> becomes templated in Phase 3b. See #2428" — which predates the #2461 walkback (the templated form lives as TypedChannel, while Channel stays non-template). Worth a one-line cleanup but doesn't block closing this issue.

    🤖 Reviewed with Claude Code

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

    area: coretype: feature

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions