Skip to content

feat(channels): declarative DriverCapabilities + pinGroups() + central resolver (replaces canHandle) #3186

Closed

Description

@zackees

Goal

Replace today's binary IChannelDriver::canHandle(const ChannelData*) runtime predicate with a declarative DriverCapabilities descriptor that each driver publishes once. The Channel Manager owns all dependency-resolution logic against the union of those descriptors — drivers stay dumb capability-publishers and don't need to know about other channels in a bulk request.

The bar: a sketch that declares addLeds<APA102, /*data=*/9, /*clock=*/10> should get a clear, actionable error if no driver can drive that pin pair — not today's "No compatible driver found" silent drop — and the resolver should also handle the multi-channel case ("9 strips, RMT5 only has 8 channels → put 1 on PARLIO") in a single planning pass, not N×M virtual calls.

Today's surface (audit)

src/fl/channels/driver.h:150-161:

struct Capabilities {
    bool supportsClockless;
    bool supportsSpi;
};

IChannelDriver::canHandle(const ChannelData*) implementations are uniformly trivial (file refs in #3176):

  • RMT5: return !data->isSpi();
  • PARLIO: return !data->isSpi();
  • SPI: return data->isSpi();
  • I2S: return !data->isSpi();
  • LCD_CLOCKLESS: return !data->isSpi();

Internal pin tables exist per-platform (e.g. isValidParlioOutputPin() at parlio.cpp.hpp:42) but aren't exposed. Manager-side, selectDriverForChannel() (manager.cpp.hpp:380-420) iterates drivers and takes the first true — no second pass, no swap, no fallback chain. Failure logs FL_ERROR and silently drops at channel.cpp.hpp:437-439.

Peripheral constraints — brainstorm

Before nailing down types, here's the catalog of things real LED-driver peripherals constrain in this codebase. Every row has to be expressible declaratively for this design to work.

Constraint Driver-by-driver example How the data model expresses it
Pin: fully flexible RMT5 — any GPIO output PinSet{kind = AnyOutputPin}
Pin: allowlist PARLIO — specific GPIO matrix subset; ESP32 SPI GPIO_MUX path PinSet{kind = Allowlist, pins = {...}}
Pin: fixed (single) LPUART instance N's TX pin; ESP32 SPI IO_MUX-optimal pins PinSet{kind = Allowlist, pins = {one_pin}}
Pin: not applicable Clock pin on a clockless group PinSet{kind = None}
Pin pair: both fixed ESP32 SPI2 IO_MUX (MOSI=11, SCK=12) Both data + clock PinSets have size-1 allowlists
Pin pair: shared clock, flex data FlexIO instance — one timer pin + N shifter data pins data_pins = allowlist of N pins, clock_pins = size-1 allowlist
Pin pair: both flexible Some bitbang SPI fallbacks Both PinSets = AnyOutputPin
Pin pair: data flex, clock fixed ObjectFLED SPI candidates (TBD #3176) data_pins = allowlist of acceptable mates, clock_pins = size-1
Pins must be contiguous (bulk) RP2040 PIO side-set, STM32 LTDC parallel, FlexIO shifter cascade PinGroup::pins_must_be_contiguous = true; resolver enforces no-gap in bulk request bitset
Frequency: SPI range ESP32 SPI: 78 kHz – 80 MHz (IO_MUX) FreqRange{min_hz, max_hz} on the SPI group or driver
Frequency: clockless range WS2812 only at ~800 kHz; UCS7604 at 800 kHz or 1.6 MHz FreqRange{min_hz, max_hz}
Frequency: unspecified PARLIO can hit any rate in its divider range — caller doesn't care FreqRange::any() sentinel
Frequency: fixed UART baud locked to a single rate FreqRange::exactly(hz)
Channel cap: per group FlexIO1 has 4 shifters PinGroup::max_concurrent = 4
Channel cap: driver total ESP32 SPI has 2 host instances (SPI2 + SPI3) DriverCapabilities::max_total_channels = 2
Channel cap: unbounded Bitbang max_total_channels = 0 sentinel
Synchronized channel start PARLIO — all lanes latch on the same clock edge flags.synchronized_start
Independent channel start RMT5 — each channel fires independently flag absent
DMA can't reach PSRAM ESP32 GDMA on some SKUs flags.requires_dma_memory
Open-drain capable Some chipsets (UCS512) want open-drain flags.open_drain_capable
Mixed protocols within driver FlexIO — SPI shifter + clockless shifter on same instance OK flags.mixed_protocols_ok
Bit-width / lane-count modes PARLIO 8-lane vs 16-lane; FlexIO 8/16/32-bit shifter modes Enumerate one PinGroup per mode (different max_concurrent + frequency). No dedicated field needed.
Chipset support A driver may support WS2812 but not UCS7604 — but this is purely a function of timing range. Falls out of DriverCapabilities::t*_range. No chipset allowlist — if the chipset's nominal timing fits, it's supported.
Clockless timing range A bit-bang encoder may hit T0H ∈ [200ns, 500ns] only DriverCapabilities::t0h_range, t0l_range, t1h_range, t1l_range
Priority RMT5 preferred over bitbang DriverCapabilities::priority

Deferred to v2 (not in initial design — flagged below in Open Questions):

  • SPI mode (CPOL/CPHA) — most LED chipsets are Mode 0; nobody needs mode flexibility today.
  • MSB/LSB first — FastLED is MSB-first; would surface only if a chipset demands LSB-first.
  • Min frame alignment / DMA descriptor count — relevant for very small frames; nobody hits this today.
  • Cross-group budget sharing within one driver instance (FlexIO's "4 total shifters shared between the clockless and SPI groups on instance 1"). Punted.

The sentinel approach for "unspecified" is uniform: FreqRange::any(), NanosRange::any(), max_total_channels = 0. The resolver treats each of these as "no constraint, skip this check."

Design — declarative capabilities, centralized resolution

Two halves: a richer capability descriptor the driver returns, and a resolver in the Channel Manager that does the actual matching.

1. The data types

namespace fl {

enum class Protocol : u8 {
    Clockless = 0,
    Spi       = 1,
};

// Frequency range with explicit "any" sentinel. All-zero is intentionally
// NOT the unspecified state — that'd silently match every legitimate
// frequency request. Use any() / exactly() / atLeast() / atMost() for
// clarity.
struct FreqRange {
    u32 min_hz;
    u32 max_hz;

    static constexpr FreqRange any()            { return {0u, 0xFFFFFFFFu}; }
    static constexpr FreqRange exactly(u32 hz)  { return {hz, hz}; }
    static constexpr FreqRange atLeast(u32 hz)  { return {hz, 0xFFFFFFFFu}; }
    static constexpr FreqRange atMost(u32 hz)   { return {0u, hz}; }

    constexpr bool isUnspecified() const {
        return min_hz == 0u && max_hz == 0xFFFFFFFFu;
    }
    constexpr bool contains(u32 hz) const {
        return hz >= min_hz && hz <= max_hz;
    }
};

// Same shape for the clockless timing fields.
struct NanosRange {
    u32 min_ns;
    u32 max_ns;
    static constexpr NanosRange any() { return {0u, 0xFFFFFFFFu}; }
    constexpr bool isUnspecified() const {
        return min_ns == 0u && max_ns == 0xFFFFFFFFu;
    }
    constexpr bool contains(u32 ns) const {
        return ns >= min_ns && ns <= max_ns;
    }
};

// Discriminator-tagged pin set. The four states match the brainstorm
// table's "Pin" rows directly.
enum class PinSetKind : u8 {
    None,           // slot not applicable (e.g. clock_pins on Clockless)
    AnyOutputPin,   // any GPIO output (RMT5-style flexibility)
    Allowlist,      // only the pins listed; size=1 expresses "fixed pin"
};

struct PinSet {
    PinSetKind kind;
    fl::span<const i16> pins;  // empty unless kind == Allowlist

    constexpr bool accepts(i16 p) const {
        if (kind == PinSetKind::None) return false;
        if (kind == PinSetKind::AnyOutputPin) return p >= 0;
        // Allowlist:
        for (auto q : pins) { if (q == p) return true; }
        return false;
    }
};

// One self-contained hardware "group" the driver exposes. Many drivers
// have multiple groups (FlexIO has 4 instances; RMT has N channels;
// LPUART has 8 instances). Each group has its own pin pool, its own
// concurrency limit, and may have its own frequency range.
struct PinGroup {
    u16 instance_id;          // opaque to resolver; just an ID
    Protocol protocol;        // Clockless | Spi (group-level)

    // The pin layout. Pairing pattern is implicit in the (data_pins,
    // clock_pins) kind combination — no separate enum needed.
    //   Clockless: clock_pins.kind = None
    //   SPI both-fixed: both kind=Allowlist, size=1
    //   SPI shared-clock: data_pins=Allowlist size N, clock_pins=Allowlist size 1
    //   SPI both-flex: both kind=AnyOutputPin
    PinSet data_pins;
    PinSet clock_pins;

    u8 max_concurrent;        // how many data_pins can be active at once

    // Frequency range for this group's clock.
    //   Clockless: bit rate (e.g. 800 kHz for WS2812)
    //   SPI: SCLK frequency
    // FreqRange::any() = "no per-group constraint, fall back to the
    // driver-level *_frequency field."
    //
    // Best-effort note: drivers backed by PLL dividers can only hit a
    // discrete set of rates within the range. The resolver does NOT
    // enforce divisor-exactness — it accepts any request inside the
    // range, and the driver internally rounds to the nearest divisor
    // at-or-below the requested rate. Good enough for LED chipsets
    // (generous timing margins); avoids leaking divider math into the
    // schema.
    FreqRange frequency;

    // Groups sharing a non-zero shared_clock_domain_id must all run at
    // the same frequency — they're physically wired to the same clock
    // source (PARLIO timer, FlexIO instance timer, etc.). The resolver
    // rejects requests with conflicting frequency_hz across groups in
    // the same domain.
    // 0 = "independent clock" (the common case — RMT5, ESP32 SPI, ...).
    u8 shared_clock_domain_id;

    // Groups sharing a non-zero shared_budget_id draw concurrent slots
    // from one pool. Pool size lives on the FIRST group with this ID
    // (its max_concurrent IS the pool size); subsequent groups with
    // the same ID re-use it. Models the FlexIO "4 shifters split
    // between SPI and clockless groups on the same instance" case.
    // 0 = "private cap, max_concurrent is mine alone" (common case).
    u8 shared_budget_id;

    // True iff a bulk request's `data_pins` bitset must be contiguous
    // (the set bits form an unbroken run with no holes). Real cases:
    //   - RP2040 PIO side-set / `set pins` / `mov pins` — base pin +
    //     consecutive offsets within the state machine's pin range.
    //   - STM32 LTDC / I8080 LCD modes — parallel data bus emits
    //     sequential GPIOs.
    //   - FlexIO shifter cascade — shifters in cascade share a base
    //     pin and use consecutive offsets.
    // Single-pin requests trivially satisfy this (one bit is a
    // contiguous run of length 1). Default false.
    bool pins_must_be_contiguous;
};

// Tiny constant-header descriptor — cheap to return by value, no
// storage-lifetime worries. The bulk group data is delivered separately
// via pinGroups().
//
// Note: there is intentionally NO `supported_chipsets` field. Chipset
// support is a derived consequence of timing — if the chipset's
// nominal T0H/T0L/T1H/T1L all fall within this driver's t*_range
// fields, the driver can drive it. New chipsets work automatically
// without any driver update.
struct DriverCapabilities {
    fl::string_view name;          // for diagnostics, e.g. "RMT5"
    u8 priority;                   // higher = preferred
    bool supports_clockless;
    bool supports_spi;
    u8 max_total_channels;         // aggregate cap; 0 = "no limit"

    // Aggregate frequency ranges. Used when a group's `frequency` is
    // `any()`. FreqRange::any() at driver level = "no global constraint
    // either" → the resolver treats any requested frequency as OK.
    FreqRange clockless_frequency;
    FreqRange spi_frequency;

    // Clockless timing-encoder range — the ONLY chipset-support gate.
    // NanosRange::any() = "this driver doesn't impose a timing
    // constraint on this component" (e.g. DMA-fed PARLIO can hit
    // anything its dividers allow).
    NanosRange t0h_range;
    NanosRange t0l_range;
    NanosRange t1h_range;
    NanosRange t1l_range;

    // Peripheral-flavor flags. Default zero = neutral / no claim.
    struct Flags {
        u8 synchronized_start    : 1;  // all groups start in lockstep
        u8 requires_dma_memory   : 1;  // DMA can't reach PSRAM
        u8 open_drain_capable    : 1;
        u8 mixed_protocols_ok    : 1;  // CL+SPI on same group instance OK
        u8 reserved              : 4;
    } flags;
};

}  // namespace fl

2. IChannelDriver surface — drivers publish data; base class does the matching

Drivers implement only two pure-virtual data accessors. They do not implement compatibility logic themselves. The matching virtuals have base-class default implementations that delegate to a free function (§3) operating purely on the published data.

class IChannelDriver {
public:
    // ===== Data accessors — drivers MUST implement ============

    // Tiny constant header — returned by value. Usually backed by a
    // `static constexpr DriverCapabilities` inside the driver.
    virtual DriverCapabilities capabilities() const = 0;

    // Bulk group data — non-owning view into driver-owned storage.
    // Most drivers point at a `static constexpr PinGroup kGroups[N]`
    // in `.rodata` (zero RAM, zero alloc). Drivers that need to compute
    // groups dynamically hold the table as a member built once at
    // construction and return a span over it.
    virtual fl::span<const PinGroup> pinGroups() const = 0;

    // ===== Matching virtuals — base class implements; drivers
    //       DO NOT override (in 99% of cases). Default impl is the
    //       only impl drivers ever need. ====================

    virtual HandleResult canMatch(const ChannelRequest& r) const {
        return fl::canMatch(capabilities(), pinGroups(), r);
    }

    virtual HandleResult canMatchBulk(const BulkChannelRequest& r) const {
        return fl::canMatchBulk(capabilities(), pinGroups(), r);
    }

    // (Existing methods unchanged: instance lifecycle, show(),
    // registerWithManager(), etc.)
};

Driver implementer's mental model: "I publish what I can do. I don't implement how matching works."

The matching virtuals exist as a hook so a driver with truly dynamic constraints (an instance that goes unhealthy mid-session, a SKU detected at runtime that changes between match calls) can override — but this should be vanishingly rare. The default is the only impl 99% of drivers ever use.

Trivial test fixtures fall out for free: supply capabilities() + pinGroups(), get correct canMatch behavior with zero boilerplate.

When to use N groups of max_concurrent=1 vs 1 group of max_concurrent=N

This distinction matters and is easy to get wrong. The rule:

  • N groups of max_concurrent=1 — when each "slot" is a truly independent hardware resource. Each picks its own divider, can run a different chipset, has its own pin from its own allowlist; failures isolate per slot. Examples: RMT5 — each RMT channel is independent (8 groups on ESP32-S3, 4 on -S2 / classic dispatch); LPUART — each instance is independent (8 groups on Teensy 4); ObjectFLED any-pin — each pin's timer is independent.

  • 1 group of max_concurrent=N — when one peripheral instance drives N pins as a single ganged operation sharing a clock, a timer, a DMA channel, and a synchronized start. Examples: PARLIO 16-lane on one instance (one timer drives 16 lanes); FlexIO instance (4 shifters share one timer); I2S parallel mode.

  • Mixed (M independent ganged groups) — drivers with M independent instances each driving N ganged lanes: M groups of max_concurrent=N. Example: a hypothetical chip with 2 PARLIO instances each capable of 8-lane output → 2 groups, each max_concurrent=8.

The same BulkChannelRequest (a bitset of N pins) means different things depending on which kind of group it lands in:

  • Against an independent-slot driver (RMT5): the bulk request fans out — resolver picks N groups, one pin per group. Each runs independently with its own divider.
  • Against a ganged-lanes driver (PARLIO): the bulk request lands as one parallel ganged operation; all N pins share the group's clock, lockstep timing, etc. — the entire bitset goes into a single group's max_concurrent budget.

Writing a multi-channel-but-independent driver as "1 group with capacity N" loses real properties: per-channel divider selection (so different chipsets per channel), per-channel diagnostics ("LED strip 3 went to RMT channel 5"), and per-channel failure isolation. When in doubt: N groups of capacity 1.

3. Compatibility is a free function — driver-agnostic, testable in isolation

namespace fl {

// Pure free functions. No driver instance required. Operate solely on
// data structs. This is what IChannelDriver::canMatch() delegates to
// by default, and what the manager-side resolver calls directly.
HandleResult canMatch(
    const DriverCapabilities& caps,
    fl::span<const PinGroup>  groups,
    const ChannelRequest&     request);

HandleResult canMatchBulk(
    const DriverCapabilities& caps,
    fl::span<const PinGroup>  groups,
    const BulkChannelRequest& request);

}  // namespace fl

Single source of truth for the matching algorithm (§6).

Testing benefit — no platform, no driver class, no peripheral mocks:

FL_TEST(CanMatch, AcceptsAnyClocklessPinForRmtCaps) {
    DriverCapabilities caps = makeRmtSnapshot();              // synthetic
    PinGroup groups[]       = { makeRmtAnyPinGroup() };       // synthetic
    ChannelRequest req{Protocol::Clockless, /*pin*/4, -1,
                       kWs2812Timing, fl::nullopt};
    REQUIRE(fl::canMatch(caps, groups, req) == HandleResult::Yes);
}

FL_TEST(CanMatchBulk, RejectsNineLanesOnEightSlots) {
    DriverCapabilities caps = makeRmtSnapshot();
    PinGroup groups[]       = { makeRmtAnyPinGroup() };       // max_concurrent=8
    BulkChannelRequest req  = makeBulkRequest(/*N=*/9);
    REQUIRE(fl::canMatchBulk(caps, groups, req) == HandleResult::NoCapacity);
}

The entire compatibility matrix can be covered with synthetic struct fixtures.

4. ChannelRequest / BulkChannelRequest — passive inputs to the free function

Requests are the input to canMatch / canMatchBulk, not a first-class API surface. Sketches don't construct them directly — addLeds<>() does, internally, before handing to the resolver. They're shown here for completeness only.

struct ChannelRequest {
    Protocol  protocol;
    i16       data_pin;
    i16       clock_pin;                       // -1 for Clockless
    ChipsetClocklessTiming timing;             // tolerance windows; empty for Spi
    fl::optional<u32>      frequency_hz;       // mostly SPI override
};

struct BulkChannelRequest {
    Protocol  protocol;
    fl::bitset_fixed<128>  data_pins;          // bit N set = include pin N
    i16                    clock_pin;          // -1 / single shared clock for Spi
    ChipsetClocklessTiming timing;
    fl::optional<u32>      frequency_hz;
};

There's no ChipsetId and no chipset-allowlist machinery on either struct. The chipset tag's only job is to supply the ChipsetClocklessTiming windows.

5. Resolver — owns the assignment logic, calls the free canMatch

namespace fl {

enum class HandleResult : u8 {
    Yes,
    NoProtocol,
    NoPin,
    NoPinPair,
    NoFrequency,    // requested frequency out of range
    NoTiming,       // chipset's tolerance windows don't fit driver's
                    // clock granularity / counter width
    NoCapacity,     // driver/group full
};

struct DriverAssignment {
    fl::vector<IChannelDriver*> driver_per_channel;     // size N
    fl::vector<HandleResult>    rejection_per_channel;  // size N
    bool fully_resolved = false;
};

// Single entry point. Manager calls this once per FastLED.show() setup.
// Drivers are touched at most twice each (capabilities() + pinGroups())
// — never N times where N = request count. Per-request matching uses
// `fl::canMatch()` directly on the cached data, bypassing the virtual
// hook for cache-friendly batch processing.
DriverAssignment resolveDriverAssignments(
    fl::span<const ChannelRequest>  requests,
    fl::span<IChannelDriver* const> drivers);

}  // namespace fl

6. Resolution algorithm

Single-pass, priority-bounded, capacity-aware:

  1. Snapshot — for every registered driver D:

    • auto caps = D.capabilities() (tiny, by value).
    • fl::span<const PinGroup> groups = D.pinGroups() (non-owning view).
    • Sort drivers by caps.priority descending.
  2. Candidate enumeration — for each request r[i] × each driver D:

    • Call fl::canMatch(caps_of_D, groups_of_D, r[i]). The free function walks D's groups in order and returns the first Yes, or the most-informative No* reason if all groups reject.
    • Record (driver, group_index) if Yes. The free function exposes which group matched via an optional out-param.
  3. Greedy assignment — iterate requests in declaration order. For each request, pick the highest-priority candidate (D, g) whose group has free max_concurrent slots AND whose driver hasn't hit max_total_channels. Decrement counters.

  4. Recovery pass — for any unassigned request whose best candidate was full, attempt a single swap: find an already-assigned request that has an alternate same-or-higher-priority candidate; move it; place the new request in the freed slot. One-hop only.

  5. Report — DriverAssignment lists driver per request and a HandleResult per unassigned request. The check that failed for every candidate becomes the reason.

Resolver complexity: O(N · M · G) where N = requests, M = drivers, G = max groups per driver. Sub-millisecond on any platform.

Internals of fl::canMatch (for reference): walk groups in order; for each group check protocol → pins → frequency → timing in cheapest-to-most-expensive order; return first Yes or accumulate the strongest No*. For SPI the timing check is skipped; for Clockless the timing check runs the divider-loop algorithm against the chipset's tolerance windows. For bulk requests, after the pin-allowlist check, an extra step verifies contiguity when g.pins_must_be_contiguous is set:

constexpr bool isContiguous(const fl::bitset_fixed<128>& b) {
    if (b.none()) return true;
    auto first = b.findFirst();         // lowest set bit
    auto last  = b.findLast();          // highest set bit
    return b.count() == u32(last - first + 1);
}

Single popcount + first/last bit-scan — three single-cycle ops on every arch with a clz/ctz/popcount instruction.

Why "capabilities" beats "ask the driver"

  • One source of truth per driver. Pin allowlist + frequency range + chipset table live next to the driver in one descriptor; no risk of getter drift.
  • Cacheable / constexpr-friendly. A static constexpr DriverCapabilities lives in .rodata, zero RAM cost, and lets addLeds<> static-assert pin validity at compile time.
  • Pure resolution logic. Manager-side resolver is unit-testable in isolation against synthetic capability structs; no driver mocking needed.
  • Pluggable strategies later. If a board needs "spread evenly," only the resolver function changes — every driver's descriptor stays the same.
  • Better diagnostics. Resolver can walk every driver's groups to print "pins {9,10} for APA102: nearest valid pairs are {11,12} on SPI2, {38,39} on FlexIO1" instead of today's "no compatible driver found".
  • No bulk-API plumbing in drivers. Driver authors don't have to think about multi-channel constraints.

Use-case walkthroughs

Flexible clockless, single pin: addLeds<WS2812, 4>

Request: {Clockless, WS2812, data_pin=4, clock_pin=-1, frequency_hz=nullopt}

Resolver walks RMT5's group {data_pins=AnyOutputPin, clock_pins=None} → pin 4 accepted → frequency check skipped (request didn't set one) → candidate. PARLIO group also matches. Greedy picks RMT5 (higher priority).

Fixed SPI pin pair (peripheral-hardwired): addLeds<APA102, 11, 12, BGR> on ESP32

Request: {Spi, APA102, data_pin=11, clock_pin=12, frequency_hz=nullopt}

ESP32 SPI driver's IO_MUX group:

static constexpr i16 kSpi2DataPin[]  = {11};  // MOSI fixed
static constexpr i16 kSpi2ClockPin[] = {12};  // SCK fixed
static constexpr PinGroup kSpi2IoMux = {
    .instance_id   = 2,
    .protocol      = Protocol::Spi,
    .data_pins     = {PinSetKind::Allowlist, kSpi2DataPin},   // size=1 → fixed
    .clock_pins    = {PinSetKind::Allowlist, kSpi2ClockPin},  // size=1 → fixed
    .max_concurrent= 1,
    .frequency     = FreqRange{78'000u, 80'000'000u},  // SPI2 IO_MUX range
};

Both accepts() calls succeed. Frequency request was nullopt → no constraint added. Driver matches. If the user had requested frequency_hz = 200_000_000u, the resolver would reject with NoFrequency and the diagnostic would say "SPI2 supports 78 kHz – 80 MHz."

Same SPI peripheral, GPIO_MUX fallback path: addLeds<APA102, 4, 5> on ESP32

ESP32 SPI can also drive any GPIO via GPIO_MUX, but at degraded max frequency (≈40 MHz vs 80 MHz). Expressed as a separate group on the same driver:

static constexpr PinGroup kSpi2GpioMux = {
    .instance_id   = 2,
    .protocol      = Protocol::Spi,
    .data_pins     = {PinSetKind::AnyOutputPin, {}},
    .clock_pins    = {PinSetKind::AnyOutputPin, {}},
    .max_concurrent= 1,
    .frequency     = FreqRange::atMost(40'000'000u),
};

Request {Spi, APA102, 4, 5, freq=10MHz} → kSpi2GpioMux accepts pins, frequency 10 MHz ≤ 40 MHz → candidate. Greedy prefers the IO_MUX group's higher-frequency-range candidate when the requested pin pair also matches it; falls back to GPIO_MUX only when needed.

Shared-clock FlexIO instance: addLeds<APA102, 9, 16>

FlexIO1 has one timer pin and N shifter data pins:

static constexpr i16 kFlexIO1Data[] = {9, 10, 11, 12};  // shifter data pins
static constexpr i16 kFlexIO1Clk[]  = {16};             // timer/clock pin
static constexpr PinGroup kFlexIO1Spi = {
    .instance_id   = 1,
    .protocol      = Protocol::Spi,
    .data_pins     = {PinSetKind::Allowlist, kFlexIO1Data},
    .clock_pins    = {PinSetKind::Allowlist, kFlexIO1Clk},   // shared, size=1
    .max_concurrent= 4,
    .frequency     = FreqRange::atMost(30'000'000u),
};

Request {Spi, APA102, data=9, clock=16} matches. Request {Spi, APA102, data=9, clock=10} rejects with NoPinPair because 10 isn't in clock_pins.

LPUART per-instance fixed TX pin: addLeds<WS2812, 24>

LPUART instance 6 has TX hardwired to GPIO 24:

static constexpr i16 kLPUART6Tx[] = {24};
static constexpr PinGroup kLPUART6 = {
    .instance_id   = 6,
    .protocol      = Protocol::Clockless,
    .data_pins     = {PinSetKind::Allowlist, kLPUART6Tx},  // fixed
    .clock_pins    = {PinSetKind::None, {}},
    .max_concurrent= 1,
    .frequency     = FreqRange::exactly(800'000u),  // WS2812 bit rate
};

addLeds<WS2812, 24> matches. addLeds<WS2812, 25> rejects with NoPin (25 isn't in any LPUART instance's pin allowlist). Diagnostic walks LPUART's 8 groups to suggest "valid LPUART TX pins: {24, 7, 8, ...}".

Bulk multi-channel with driver-total cap: 9 strips, RMT5 has 8

9 clockless requests, all on different pins. RMT5 publishes 8 independent groups, one per RMT channel, each max_concurrent = 1; max_total_channels = 8. PARLIO publishes one group with max_concurrent = 8 (ganged lanes).

Resolver iterates 9 requests; the first 8 each land in a distinct RMT5 group (channels 0..7), each independently picking its own divider for its chipset. 9th request: every RMT5 group full + max_total_channels cap reached → falls to PARLIO. Assigned. No silent drop.

The fan-out across N RMT groups is what makes per-channel divider choice possible — channel 0 can run WS2812 at divider 1, channel 5 can run a slower chipset at divider 4. A "1 RMT group, capacity 8" model would lose that.

Chipset support emerges from timing, not an allowlist

A new chipset UCS9999 (hypothetical) requires T0H = 250ns, T0L = 1000ns, T1H = 750ns, T1L = 500ns.

RMT5 has t0h_range = NanosRange{50, 5000}, similarly wide for the other three → timing falls within → candidate. No driver code changes needed when this chipset ships.

A hypothetical bitbang driver with t0h_range = NanosRange{400, 1000} rejects UCS9999 with NoTiming because 250 ns is below the driver's minimum. Same answer: emergent from timing fit, not from a maintained allowlist.

Synchronized-start requirement (advisory): four lanes in lockstep

flags.synchronized_start = 1 on PARLIO. Not a rejection criterion (the resolver doesn't require sync) but the resolver does emit a warning if a sketch's 4-strip group lands across two drivers where one is synchronized_start = 1 and the other isn't — the user probably expected sync and won't get it.

Mixed protocol within FlexIO1: 1 SPI + 3 clockless on the same instance (shared shifter pool)

FlexIO1 has 4 shifters total, split arbitrarily between SPI and clockless modes. Modeled as two groups with the same shared_budget_id:

// SPI group on FlexIO1 — pool size 4 lives here.
PinGroup{
    .instance_id = 1, .protocol = Spi,
    .data_pins = {Allowlist, kFlexIO1Data},
    .clock_pins = {Allowlist, kFlexIO1Clk},   // size=1 shared clock
    .max_concurrent = 4,                       // POOL SIZE (first group with shared_budget_id=1)
    .shared_budget_id = 1,
}

// Clockless group on FlexIO1 — shares the pool.
PinGroup{
    .instance_id = 1, .protocol = Clockless,
    .data_pins = {Allowlist, kFlexIO1Data},
    .clock_pins = {None, {}},
    .max_concurrent = 4,                       // re-uses same pool — value ignored, only first group's count matters
    .shared_budget_id = 1,                     // same pool
}

Resolver tracks pool occupancy: 1 SPI request consumes 1 of 4; 3 clockless requests consume 3 more → pool full. A 4th clockless request gets NoCapacity because all 4 shifters are claimed.

Frequency lock-step within a driver: PARLIO 4-lane group

PARLIO's lanes share one timer. Modeled as 4 groups (one per lane) all carrying shared_clock_domain_id = 1:

PinGroup{instance=0, ..., frequency = FreqRange{100_kHz, 40_MHz}, shared_clock_domain_id = 1}
PinGroup{instance=1, ..., frequency = FreqRange{100_kHz, 40_MHz}, shared_clock_domain_id = 1}
// ... 2 more identical groups

Resolver behavior: first request landing in any of these groups locks the clock domain to its frequency_hz. Subsequent requests in the same domain must match (or be nullopt, taken as "use whatever the first one picked"). A second request with an incompatible frequency_hz is rejected with NoFrequency and the diagnostic names the existing lock.

Migration plan

Two-step, backward compatible:

  1. Add capabilities() and pinGroups() alongside today's canHandle(). Manager prefers the new surface when present; falls back to canHandle() for unmigrated drivers. Default capabilities() synthesizes a minimal descriptor from today's Capabilities. Default pinGroups() returns empty.
  2. Migrate drivers one at a time. Order: RMT5 (simplest) → PARLIO → SPI → LCD_CLOCKLESS → I2S → FlexIO → LPUART → ObjectFLED. Each migration fills in real allowlist + frequency + flag data.
  3. Delete legacy canHandle() once all drivers migrated.

The resolver lands with step 1 — it works with either the new descriptors or the synthesized-from-legacy ones.

Adversarial scenarios — covered vs deferred

These were checked against real MCU peripherals during design. Covered ones map directly to the data model; deferred ones are real but not worth modeling for v1 (rare in LED workloads, or live outside the driver's purview).

Covered by the data model:

  • Discrete PLL-divider frequencies → handled via best-effort matching (driver internally rounds to nearest divisor ≤ requested); resolver treats FreqRange as inclusive.
  • Frequency × bit-width coupling (PARLIO max-freq drops with width) → enumerate multiple PinGroups per (bw, freq) combo.
  • Cap depends on bit-width (FlexIO 4-shifter / 2-channel-32-bit) → multiple groups per bw.
  • Shared shifter pool across CL+SPI groups in same instance → shared_budget_id.
  • One timer driving all lanes (PARLIO) → shared_clock_domain_id.
  • IO_MUX vs GPIO_MUX frequency split → separate groups.
  • Per-chip-SKU pin tables → driver picks tables at compile time / construction.

Deferred — exists in real MCUs but out of scope for v1:

  • Inter-driver mutual exclusion (RMT ↔ LEDC sharing clock domain on ESP32). Lives at the board/runtime layer, not in driver-static capability. Future: a separate driver-conflict registry consumed by the manager.
  • DMA channel pool exhaustion (GDMA finite global pool). Rarely binds for LED workloads (most LED frames use 1-2 DMA channels). Defer.
  • Per-chipset metadata (UCS512 requires open-drain output). The chipset side needs metadata, not the driver side. Belongs in the chipset spec, not DriverCapabilities. Out of scope for this issue.
  • Strapping-pin per-pin caution metadata (ESP32 GPIO 0/2/12/15 boot-fragile). Board-level concern. Drivers either include them (let user accept) or exclude them — schema doesn't need a tri-state.
  • SPI mode (CPOL/CPHA), MSB/LSB-first, DMA alignment, frame size limits. Real peripheral constraints but no current FastLED workload trips on them. Additive — easy to extend PinGroup flags later without breaking the wire format.
  • Asymmetric capacity ("1 fast channel OR N slow channels"). Not present in any FastLED-relevant peripheral.

Skipped — checked but not a real MCU constraint:

  • Differential SPI clocks (no LED chipset uses this).
  • Positional pin constraints (data pin > clock pin) — no peripheral does this.
  • Pin-bank concurrency limits for SPI (peripheral handles sequencing internally).
  • Forbidden specific pin pairs within an otherwise-OK set (real for LCD/parallel buses, not for LED SPI).

Open design questions

  • Pluggable resolver strategy. Default greedy + one-hop swap is fine for v1; pluggable strategy gated on real demand.
  • Compile-time resolution. When addLeds<> calls are static, constexpr resolver could static-assert at compile time. Out of scope for v1.
  • Storage ownership. Driver owns the PinGroup table. Static (.rodata) for simple drivers; member-owned (fl::vector populated at construction) for runtime-configurable ones. Interface is identical.

Acceptance

  • fl::Protocol, fl::FreqRange, fl::NanosRange, fl::PinSet, fl::PinSetKind, fl::PinGroup, fl::DriverCapabilities, fl::ChannelRequest, fl::HandleResult defined in src/fl/channels/capabilities.h. No ChipsetId field — chipset support is derived from timing fit.
  • FreqRange::any() / exactly() / atLeast() / atMost() and matching NanosRange::any() static constructors are constexpr.
  • PinSet::accepts(i16) is constexpr for compile-time validation in addLeds<> paths.
  • IChannelDriver::capabilities() pure-virtual added with default impl synthesizing from today's legacy Capabilities + canHandle().
  • IChannelDriver::pinGroups() pure-virtual added returning fl::span<const PinGroup>; default returns empty.
  • IChannelDriver::canMatch(ChannelRequest) and canMatchBulk(BulkChannelRequest) non-pure virtuals added with base-class default impls delegating to fl::canMatch / fl::canMatchBulk. No driver implements matching logic in v1.
  • fl::canMatch(caps, groups, request) and fl::canMatchBulk(caps, groups, bulk_request) land in src/fl/channels/can_match.h / can_match.cpp.hpp as pure free functions — no driver dependencies, fully testable in isolation against synthetic struct fixtures.
  • fl::resolveDriverAssignments(requests, drivers) lands in src/fl/channels/resolver.h / resolver.cpp.hpp.
  • Resolver does zero per-channel virtual calls — calls capabilities() + pinGroups() once per driver upfront, then runs free fl::canMatch against cached snapshots.
  • At least one driver migrated to a real static constexpr DriverCapabilities descriptor (recommend RMT5).
  • Unit tests cover:
    • Bulk 9 channels on RMT5-only → 8 RMT5 + 1 fallback.
    • SPI fixed pin pair rejection surfaces NoPinPair with nearest-valid-pair diagnostic.
    • Frequency-out-of-range rejection surfaces NoFrequency.
    • Driver-level max_total_channels enforced separately from per-group max_concurrent.
    • PinSet::AnyOutputPin accepts any positive pin; PinSet::None rejects all.
    • FreqRange::any() and NanosRange::any() round-trip through resolver as "no constraint."
    • shared_budget_id: 4-slot pool refuses a 5th request across mixed-protocol groups in the same instance.
    • shared_clock_domain_id: first lane locks frequency, conflicting second lane gets NoFrequency.
    • pins_must_be_contiguous: bulk request of {4, 5, 7, 8} (gap at 6) gets NoPin with diagnostic "this driver requires contiguous pins; nearest contiguous candidate of length 4 starting in range is {4, 5, 6, 7}." Bulk request of {4, 5, 6, 7} matches.
    • Zero allocations in the resolver hot path for a 16-channel request.
  • tests/fl/channels/predicate_dependency_resolution.cpp covers multi-driver greedy + one-hop swap with synthetic capability descriptors (no driver mocking).

Cross-references

Activity

  1. zackees commented on Jun 27, 2026

    @zackees
    MemberAuthor

    Closing as deferred future work. Declarative DriverCapabilities + pinGroups() + central resolver is a framework-wide refactor that would replace the current canHandle() virtual hook with declarative metadata. Substantial cross-driver change; existing canHandle() works correctly across all merged drivers (LPUART, FlexIO, ObjectFLED, FastLED-RMT, PARLIO, SPI, I2S, etc.). Re-open when there's a specific driver/dispatch limitation that the current canHandle() cannot express. Tracked at meta level under #3023.

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