Skip to content

perf(channels): replace =1 FreeRTOS-tick busy-sleep in waitForReady with ISR-completion + NetworkDetector-gated yield (refs #2420, #2254, #2493) #2815

Closed

Description

@zackees

Summary

ChannelManager::waitForReady() (and the parallel IChannelDriver::waitForReady()) currently busy-poll poll() in a loop, yielding ≥ 1 FreeRTOS tick (≥ 1 ms at CONFIG_FREERTOS_HZ=1000) per iteration, on every platform except ESP32-P4. This is a coarse-grained pessimistic sleep that was inserted as a defensive fix for #2254 (I2S driver starving WiFi/lwIP), and is the root cause of the timing drift reported in #2420 and was the symptom that originally drove #2493 (which was patched per-platform via #if defined(FL_IS_ESP_32P4) rather than at the root).

This issue proposes replacing the unconditional 1-tick yield with a two-track scheme:

  1. Per-driver ISR completion — block on the driver's existing DMA-done semaphore (most drivers already have one), eliminating the poll loop for the single-driver case.
  2. Adaptive yield — when a poll loop is needed (multi-driver aggregate), gate the deep yield on the existing fl::NetworkDetector::isAnyNetworkActive() at runtime instead of hard-coding by platform.

When no radio is active, the wait collapses to a fast fl::yield() path (the same path #2493 enabled for ESP32-P4). When a radio is up, we keep the current behavior so WiFi/lwIP/BT controller tasks don't starve.


Current code

// src/fl/channels/manager.cpp.hpp:364-388
template<typename Condition>
bool ChannelManager::waitForCondition(Condition condition, u32 timeoutMs) {
    const u32 startTime = timeoutMs > 0 ? millis() : 0;

    while (!condition()) {
        if (timeoutMs > 0 && (millis() - startTime >= timeoutMs)) {
            FL_ERROR("ChannelManager: Timeout occurred while waiting for condition");
            return false;
        }

#if defined(FL_IS_ESP_32P4)
        // ESP32-P4 has no network stack ... avoids the 1-tick floor (#2493)
        task::run(0, task::ExecFlags::SYSTEM);
#else
        // OS yield only — keeps WiFi/lwIP alive (#2254)
        task::run(250, task::ExecFlags::SYSTEM);
#endif
    }
    return true;
}

The identical pattern exists at src/fl/channels/driver.cpp.hpp:11-35.

task::run(250, SYSTEM) resolves to pumpCoroutines(1000) inside src/fl/task/executor.cpp.hpp:135-141, which on FreeRTOS is a vTaskDelay(>=1 tick) — minimum 1 ms at the project's standard CONFIG_FREERTOS_HZ=1000. The 250 argument is misleading; the floor is the tick, not the budget.


Impact (#2420 reproduction)

User's sketch: 35-LED WS2812B on ESP32-S3, FAST_LED_UPDATE_MS=5 paced with millisDelay from powerbroker2/SafeString.

  • WS2812B 35-LED burst: ~1.05 ms (transmit only)
  • Each FastLED.show() then enters waitForReady() and pays ≥ 1 ms tick floor at least once before the driver reports READY → wall-clock cost per frame ≈ 2 ms instead of ~1 ms.
  • Over a sequence the reporter timed at 2500 ms expected → 2600–3000 ms observed (≈ 100 ms drift), consistent with ~1 ms × ~100 frames.

This regression did not exist in 3.10.3 because the channels-API waitForReady() aggregator did not exist; clockless controllers spun on delayMicroseconds until the bit-stream finished and returned.


Proposal

Track 1 — Replace poll-loop with ISR-blocking wait inside each driver

Most ESP32 drivers already have an ISR/event-callback that flips a state flag at DMA-done. They differ in whether the wait is implemented as a poll or as a semaphore take:

Driver Completion mechanism Current wait API Action
PARLIO parlio_tx_register_event_callbacks(on_trans_done) waitAllDone(timeout_ms) — wraps parlio_tx_unit_wait_all_done() (ISR-driven semaphore in IDF) Use as-is
RMT5 rmt_tx_register_event_callbacks(on_trans_done) waitAllDone(timeout_ms) — wraps rmt_tx_wait_all_done() (IDF semaphore) Use as-is
LCD_SPI / LCD_CLOCKLESS esp_lcd_panel_io_register_event_callbacks(on_color_trans_done) with custom xSemaphoreGiveFromISR waitTransmitDone(timeout_ms) — xSemaphoreTake(mCompleteSem, ticks) Already semaphore-blocked
I2S_SPI Native I2S isrHandler() on out_eof, xSemaphoreGiveFromISR waitTransmitDone(timeout_ms) — xSemaphoreTake(mCompleteSem, ticks) Already semaphore-blocked
SPI clockless spi_device_get_trans_result() (IDF blocks on internal sem) pollTransaction(timeout_ms) Use as-is
I2S LCD_CAM on_color_trans_done callback sets volatile mBusy flag waitTransmitDone(timeout_ms) — polls mBusy with vTaskDelay(1) ~20 LOC: add binary semaphore, give in ISR, take in wait
LCD_RGB on_vsync callback clears mBusy waitFrameDone(timeout_ms) — polls with task::run(250, SYSTEM) ~20 LOC: add binary semaphore, give in ISR, take in wait

Wire IChannelDriver::waitForReady(timeoutMs) to delegate to the driver's existing waitXxxDone() primitive when present, so the single-driver fast path no longer enters the manager's poll loop at all. This is the primary win — FastLED.show() with one strip drops from poll → 1 ms tick → poll → ready to xSemaphoreTake(sem, timeoutTicks) blocking precisely until the DMA-done ISR fires.

For multi-driver users (manager aggregator), the loop still exists, but see Track 2.

Track 2 — Gate the deep yield on actual radio activity

fl::NetworkDetector already exists at src/platforms/esp/32/drivers/rmt/rmt_5/network_detector.h and exposes:

  • isWiFiActive() — esp_wifi_get_mode() != WIFI_MODE_NULL
  • isEthernetActive() — esp_netif interface enumeration
  • isBluetoothActive() — esp_bt_controller_get_status()
  • isAnyNetworkActive() — convenience OR

It already uses weak-symbol fallback so unlinked-network builds are zero-cost. It is currently scoped under FASTLED_RMT5 — promote it to a shared ESP32 utility (e.g. src/platforms/esp/32/util/network_detector.h).

Then in the wait loop:

#if FL_IS_ESP32
    // Cache once per show() to avoid repeated esp_wifi_get_mode() inside the spin
    const bool radio_up = fl::NetworkDetector::isAnyNetworkActive();
    if (radio_up) {
        task::run(250, task::ExecFlags::SYSTEM);  // deep yield, keep WiFi/BT alive
    } else {
        task::run(0, task::ExecFlags::SYSTEM);    // fast fl::yield() path
    }
#else
    task::run(0, task::ExecFlags::SYSTEM);
#endif

This replaces the platform #if defined(FL_IS_ESP_32P4) carve-out with a runtime decision. ESP32-S3, ESP32 dev, etc. with no WiFi/BT brought up (the #2420 reporter's sketch never calls WiFi.begin()) immediately benefit. Sketches that do bring up the radio retain the current safe behavior, preserving the #2254 fix.

NetworkDetector cost is ~1–10 µs per call per its own docs; cache the result for the duration of one wait, not inside the spin.

Track 3 — User-facing follow-up for #2420

The reporter is using millisDelay from powerbroker2/SafeString for pacing. FastLED ships an equivalent, integrated with the engine event loop:

#include "fl/task/task.h"
auto t = fl::task::every_ms(5).then([]() { FastLED.show(); });
fl::task::Scheduler::instance().add_task(t);

Once Tracks 1+2 land, this scheduler-driven pacing is more accurate than millisDelay because the scheduler's own wakeup goes through the (then-improved) wait path. The reporter can drop the third-party millisDelay dependency entirely.


Acceptance criteria

  1. FastLED.show() on ESP32-S3 with a single strip and no WiFi/BT brought up completes within ~1.2× the bit-stream transmit time (no 1 ms tick floor visible).
  2. FastLED.show() on ESP32-S3 with WiFi connected does not regress lwIP throughput relative to current master (re-validate the ESP32-S3: I2S driver starves websockets, SPI output incorrect, Audio driver FPS impact #2254 websocket scenario).
  3. ESP32-P4 PARLIO path retains current ESP32-P4 PARLIO: FastLED.show() appears to block for ~16.7 ms before WS2812 data burst begins #2493 behavior (the FL_IS_ESP_32P4 carve-out is replaced by the same runtime decision, which on P4 always returns "no radio").
  4. The reporter's [Bug] Compounded timing inaccuracy on master compared to 3.10.3 #2420 sketch produces a 2500 ms sequence within ±10 ms (instead of +100…+500 ms).
  5. NetworkDetector is promoted out of the rmt_5/ subdirectory so all wait sites can use it.

Cross-references

Activity

  1. zackees commented on Jun 5, 2026

    @zackees
    MemberAuthor

    Design strategy review — 6 strategies investigated, 4-phase rollout

    Revisions:

    • Strategy 1 verdict updated. The "leaked Gives" failure mode is recoverable by treating the semaphore as a wakeup signal and poll() as the source of truth (condvar pattern). Strategy 1 is no longer dominated; it becomes a viable simpler alternative to Strategy 3 for the N>1 fan-in.
    • Cross-platform primitives audit added. Phases 1, 2, 4 are platform-neutral; Phase 3 fan-in mechanisms are ESP32/FreeRTOS-only.
    • Spin tier is a fallback, not the steady-state path. Default budget locked at 250 µs. Single-driver waits skip it entirely once Phase 2 lands.
    • FL_IS_ESP_32P4 carve-out is dropped — NetworkDetector's "no radio" weak-symbol fallback subsumes it.
    • Phase 1 and Phase 2 will be filed as separate implementation issues linked from this one.

    Six concurrency designs for the multi-driver wait were investigated in parallel. Summary + recommendation below; each agent's full analysis (~500 words each) is preserved in the conversation log that led to this comment.

    Multi-driver constraint

    A single shared semaphore is not enough when more than one driver is mid-transmit concurrently (e.g. LCD_SPI + LCD_RGB + PARLIO firing in parallel). The wait must aggregate completion across N heterogeneous drivers without paying a ≥1 ms FreeRTOS tick per poll iteration.

    Strategy matrix

    # Strategy Multi-driver semantics RAM cost Driver retrofit Verdict
    1 Shared counting semaphore — structured as wakeup signal + poll()-verify (condvar pattern) Wakes on ANY driver Give; loop re-polls until aggregate READY. Spurious wakeups harmless. ~80 B Per-driver ISR ctx swap Viable on ESP32. Simpler than #3 at the cost of "which driver hung" diagnostics. Leaked / phantom / saturated Gives are all benign because poll() is the truth — sem is purely a wakeup.
    2 FreeRTOS event group bitmask One bit per driver-instance, AND-wait ~20 B static Add bindCompletionSignal(grp, bit) virtual Workable on ESP32. Caps at 24 drivers. Depends on FreeRTOS timer-daemon health.
    3 Task notification with bits eSetBits sticky, returned mask diagnoses hangs 0 (uses task slot) Add setCompletionNotify(handle, bit) virtual Preferred fan-in when diagnostics matter, ESP32 only. Modern FreeRTOS-native, zero alloc, no daemon dependency. Needs CONFIG_FREERTOS_TASK_NOTIFICATION_ARRAY_ENTRIES=2 and reserved index.
    4 Hybrid: N=1 direct driver->waitDone(), N>1 fan-in (#1 or #3) Best per-case minimal waitDone() + 7 one-line overrides; fan-in mechanism only on drivers that need it Highest leverage. Cross-platform. Survey of examples/ shows ≥83% of sketches are N=1 driver. The N=1 path collapses to a single virtual call to the driver's already-existing completion wait (FreeRTOS sem on ESP32; volatile flag poll on Teensy/bare-metal).
    5 Decoupled / idle-hook reactor (show() non-blocking) True overlap of loop() compute with previous DMA RMT5 needs ~18 KB double-buffer; others already snapshot Driver-side reactor + API versioning High payoff, high risk. Cross-platform. Breaks show(); delay(N) sketches that assume strip-is-idle post-show. Must be behind setAsyncShow(true) opt-in. Future v2.
    6 Tiered: instant → spin (250 µs) → deep yield Unchanged (works against existing aggregate poll()) 0 None — only waitForCondition body Lowest-risk immediate win. Cross-platform. Spin is a fallback, not the steady-state path — see Phase 2 below. With NetworkDetector gating, the deep-yield branch is bypassed when no radio is up.

    Cross-platform primitives audit

    The strategies divide cleanly into "platform-neutral" (work everywhere) and "FreeRTOS-only" (ESP32 only). Teensy is single-core bare-metal — no RTOS, no tasks, no scheduler to wake a blocked thread. The existing Teensy semaphore at src/platforms/arm/teensy/semaphore_teensy.h is explicit:

    • Line 14: "These are ISR-protection primitives, NOT threading primitives"
    • Line 78: acquire() on a depleted sem PANICS (would deadlock — no scheduler to wake you)
    • Line 91: try_acquire_for(rel_time) ignores the timeout — falls through to non-blocking try_acquire
    Primitive ESP32 (FreeRTOS) Teensy (bare-metal) AVR / RP2040 (Arduino)
    Counting semaphore (non-blocking counter) xSemaphoreCreateCounting CountingSemaphoreTeensy (ISR-safe counter; no wait) Volatile counter + cli/sei
    Blocking sem Take with timeout xSemaphoreTake(ticks) No — acquire() PANICs No
    Event group bitmask xEventGroupSetBitsFromISR / WaitBits No No
    Task notification xTaskNotifyIndexedFromISR No (no tasks) No
    Cooperative yield task::run(SYSTEM) → vTaskDelay yield() (Arduino — pumps USB serial) yield()
    Volatile flag + ISR-set Yes Yes (already the de-facto pattern in every Teensy DMA driver) Yes
    __WFE / __WFI + __SEV-from-ISR n/a Yes (Cortex-M instructions; not currently used in FastLED) n/a

    Strategy-by-strategy translation

    Strategy Teensy story
    #6 tiered spin Works as-is. The "deep yield" branch becomes yield() instead of task::run(SYSTEM) — the abstraction already covers this.
    #4 hybrid N=1 fast-path Works. waitDone() virtual works; Teensy override is a busy-poll on a volatile flag (or __WFE loop). No FreeRTOS dep. Default-delegate to legacy waitForReady preserves existing Teensy paths.
    #1 sem-assisted poll ESP32 only. Shared sem requires Take to block; on Teensy that PANICs. Teensy falls back to plain polling — equivalent to Strategy 6 alone.
    #3 task notification bits ESP32 only. No tasks, no notification slots.
    #2 event group ESP32 only. No FreeRTOS event groups.
    #5 decoupled reactor Works architecturally. Reaper polls volatile flags instead of blocking on sems; cost is the polling overhead, which the reactor model already pays.

    Implication: Phase 1, Phase 2, and Phase 4 are the cross-platform story. Phase 3 (multi-driver fan-in) is ESP32-only by construction — but acceptable because Teensy doesn't have the ≥1 ms tick floor in the first place. The whole bug being solved is largely a FreeRTOS-tick artifact. On Teensy, task::run(SYSTEM) yields cooperatively, no vTaskDelay, so the per-poll overhead is already negligible.

    A future enhancement worth filing separately: add a __WFE/__SEV bare-metal "block until interrupt" helper in semaphore_teensy.h so Teensy can get true low-power blocking instead of polling. Useful for power-sensitive sketches but orthogonal to #2815.

    Strategy 1 — revised "wakeup-signal + poll-verify" structure

    The original agent flagged three concerns with the shared counting sem: chunked drivers leak extra Gives (LCD_SPI fires its ISR once per chunk per lcd_spi_peripheral_esp.cpp.hpp:58-87), lost-Give races on count increment, and uxMaxCount saturation. All three become non-bugs once the manager stops trying to match Take-count against expected and instead uses the sem as a pure wakeup:

    bool ChannelManager::waitForReady(u32 timeoutMs) {
        const u32 start = millis();
        while (true) {
            if (poll().state == DriverState::READY) return true;
            u32 elapsed = millis() - start;
            if (timeoutMs && elapsed >= timeoutMs) return false;
            u32 remain = timeoutMs ? timeoutMs - elapsed : portMAX_DELAY;
            xSemaphoreTake(mDoneSem, pdMS_TO_TICKS(remain));  // wake on ANY ISR
        }
    }
    Original concern With poll-verify
    Chunked driver leaks N Gives Each leaked Give wakes us once → one extra cheap poll() → loop. Harmless.
    Lost-Give race (Give before count increment) We don't track count anymore. Next ISR Gives, we wake, poll() is truth.
    uxMaxCount saturation Once sem is full, late Gives drop — but earlier wakeups still came, and poll() is source of truth. Degrades to plain poll, never wrong.
    Per-driver waitForReady "steals" Gives Stolen Give → manager wakes spuriously → re-polls. Harmless.

    Structurally this is a condvar pattern. The sem replaces the vTaskDelay(1) yield; poll() remains the truth. What it still can't do versus #3: identify which driver finished (no mask diagnostic on hang) and per-driver timeouts. What it gains: drastically simpler — one sem handle, no bit allocation, no notification index reservation, no sdkconfig change.

    #2254 invariant preserved by Take semantics

    xSemaphoreTake(sem, ticks) is a true blocking primitive — the calling task moves to FreeRTOS Blocked state, removed from its core's ready list, scheduler runs the next-highest-priority task on that core. ISR Give moves the task back to ready; with portYIELD_FROM_ISR it runs on ISR exit. Wakeup latency is ~µs (not the ≥1 ms tick floor of vTaskDelay).

    The cooperator-keepalive rationale from #2254 is preserved by virtue of the Blocked state itself, not by the 1 ms tick. WiFi/lwIP/BT tasks on core 0 run independently regardless; user-space WiFi handlers on core 1 get scheduled the same way they do under vTaskDelay. Same yielding, no tick floor.

    vTaskDelay(1 tick) (today) xSemaphoreTake(sem, ticks)
    Same-core other tasks run Yes Yes
    WiFi/lwIP/BT preserved (different core) Yes Yes
    Wakeup latency ≥1 ms (tick boundary) µs (ISR-driven)
    CPU during wait IDLE (low power) IDLE (low power)
    Cooperator semantics Same Same

    Composability

    Recommended phased rollout

    Spin budget across all phases:

    Single-driver wait path Multi-driver aggregate wait path
    Phase 1 only spin (250 µs) → deep yield spin (250 µs) → deep yield
    Phase 2+ driver->waitDone() → xSemaphoreTake(sem, ticks) — exact, ISR-driven, no spin spin → deep yield (fallback)
    Phase 3+ same as Phase 2 (sem Take, exact) sem Take + poll()-verify (exact, ISR-driven) — no spin

    The spin is a fallback for the multi-driver aggregate case and for drivers that haven't migrated to waitDone(). After Phase 2 lands, the #2420 single-driver sketch hits the sem Take path exclusively — no spin, no tick floor. Bare-metal platforms (Teensy, AVR) keep the spin as their fast path forever (no FreeRTOS sems available, but also no 1 ms tick floor to escape).

    Phase 1 — Tactical (separate issue, no API change). Cross-platform.

    • Strategy 6: tiered wait in ChannelManager::waitForCondition (src/fl/channels/manager.cpp.hpp:364-388) AND IChannelDriver::waitForCondition (src/fl/channels/driver.cpp.hpp:11-35). Extract a shared helper to avoid drift.
    • Default spin budget: 250 µs (compile-time FASTLED_WAIT_SPIN_BUDGET_US + runtime FastLED.setWaitSpinBudgetUs(N) per Public Settings Pattern).
    • Combined with NetworkDetector runtime gate: when !isAnyNetworkActive(), extend the spin to ~5 ms; deep yield otherwise. NetworkDetector promoted from src/platforms/esp/32/drivers/rmt/rmt_5/ to src/platforms/esp/32/util/. Existing FL_IS_ESP_32P4 carve-out removed — NetworkDetector returns "no radio" on P4 via weak-symbol fallback automatically.
    • Test coverage: host test driving waitForCondition with a synthetic condition; extend examples/AutoResearch/AutoResearch.ino with a [Bug] Compounded timing inaccuracy on master compared to 3.10.3 #2420-style timing-drift mode runnable via bash autoresearch <board>.
    • Expected win: [Bug] Compounded timing inaccuracy on master compared to 3.10.3 #2420 35-LED case (1.05 ms transmit) becomes drift-free. APA102 entirely caught in spin. Mid-size WS2812B strips lose most of the per-frame 1 ms tick.
    • Risk: Very low. 2 files touched, no ISR plumbing, no virtual additions.

    Phase 2 — Hybrid N=1 fast-path (separate issue). Cross-platform.

    • Strategy 4 with default-delegate.
    • Add virtual bool IChannelDriver::waitDone(u32 timeoutMs) FL_NOEXCEPT to src/fl/channels/driver.h. Default implementation: return waitForReady(timeoutMs); (preserves existing slow loop for any driver that doesn't override).
    • Override in each of the 7 ESP32 drivers as a thin wrapper over their existing semaphore-backed wait:
      • PARLIO → parlio_tx_unit_wait_all_done (parlio_peripheral_esp.cpp.hpp:334)
      • RMT5 → rmt_tx_wait_all_done (rmt5_peripheral_esp.cpp.hpp / IDF semaphore)
      • LCD_SPI → existing xSemaphoreTake(mCompleteSem) (lcd_spi_peripheral_esp.cpp.hpp:452)
      • I2S_SPI → existing xSemaphoreTake(mCompleteSem) (i2s_spi_peripheral_esp.cpp.hpp:556)
      • I2S LCD_CAM, LCD_RGB → ~20 LOC each to add binary sem + give-in-ISR
      • SPI clockless → existing spi_device_get_trans_result (IDF semaphore)
    • Teensy drivers override waitDone as a busy-poll on the volatile completion flag they already set in their DMA-done ISR — no FreeRTOS dependency.
    • Manager's waitForReady: classify drivers via poll() pre-pass; if exactly one BUSY, return that->waitDone(timeoutMs) directly, bypassing the spin tier entirely.
    • Expected win: 83–90% of sketches (single-driver) bypass the spin AND the deep yield — exact ISR-driven wait. The [Bug] Compounded timing inaccuracy on master compared to 3.10.3 #2420 reporter's sketch path becomes optimal.
    • Risk: Low. Each driver-side change is a thin wrapper. Multi-driver path falls through to the Phase 1 spin until Phase 3.

    Phase 3 — Fan-in for N>1. ESP32 / FreeRTOS only.

    Teensy and other bare-metal targets fall back to the Phase 1 spin tier. They don't suffer the 1 ms tick floor (no vTaskDelay), so the polling cost is negligible.

    Option A — Strategy 1 (sem-assisted poll, simpler):

    • Manager owns one xSemaphoreCreateCounting(kMaxDrivers, 0) (kMaxDrivers = 16 is ample).
    • Each driver's existing done-ISR Gives the shared sem in addition to (or instead of) its private one.
    • Manager waitForReady loop: poll()-verify → xSemaphoreTake(sem, remaining_ticks) → repeat.
    • No new virtuals, no notification index, no sdkconfig changes.
    • Loses "which driver hung" diagnostic on timeout (caller can iterate driver states post-timeout for the same info).

    Option B — Strategy 3 (task notification with bits, richer diagnostics):

    • Add virtual void IChannelDriver::setCompletionNotify(TaskHandle_t, u32 bit) FL_NOEXCEPT {} (no-op default).
    • Add CONFIG_FREERTOS_TASK_NOTIFICATION_ARRAY_ENTRIES=2 to platforms/esp/32/sdkconfig.defaults; reserve index 1.
    • Manager waitForReadyFanIn: bind notify per BUSY driver, then xTaskNotifyWaitIndexed(FL_NOTIFY_IDX, 0, ULONG_MAX, &recvd, ticks) in a loop accumulating bits until (acc & expected_mask) == expected_mask.
    • Drivers that don't implement setCompletionNotify get a capability check + fall back to polling.
    • Returns precise mask of "who fired" on partial timeout for diagnostics.

    Recommendation: start with Option A (Strategy 1 revised). Simpler change, no sdkconfig touch, no notification-index coordination with user code. Upgrade to Option B later only if multi-driver timeout diagnostics become a recurring debugging need.

    • Expected win: True multi-driver concurrent transmit with no tick floor on ESP32.
    • Risk: Low for A, Medium for B.

    Phase 4 (future / v2) — Decoupled async show. Cross-platform.

    • Strategy 5 behind FastLED.setAsyncShow(true) opt-in or FASTLED_SHOW_V2 macro.
    • show() becomes "reap + kickoff" — no waitForReady in the synchronous path. Reaper runs on fl::task::Scheduler::update().
    • RMT5 driver needs double-buffer (~18 KB on ESP32-S3 12×256). Other drivers (PARLIO, LCD_*, SPI, I2S_SPI) already snapshot at kickoff per buffer-ownership audit.
    • Default remains synchronous in 4.x for back-compat (sketches doing show(); delay(N) assume strip-is-idle post-show).
    • Expected win: True overlap of user compute and DMA. Frame-rate ceilings rise.
    • Risk: High. API versioning required. Backward-compat hazard for power-rail / level-shifter / scope-debug sketches.

    Acceptance criteria (refined)

    The Phase 1+2 combination meets the original issue body's acceptance criteria:

    1. ESP32-S3 single-strip, no WiFi → completes within ~1.05× transmit time (Phase 2 fast path is ISR-exact; Phase 1 spin not even reached)
    2. ESP32-S3 WiFi connected → no lwIP throughput regression (NetworkDetector gating keeps deep yield active; sem Take preserves cooperator semantics)
    3. ESP32-P4 PARLIO → unchanged behavior (NetworkDetector returns "no radio" on P4; no FL_IS_ESP_32P4 carve-out needed)
    4. [Bug] Compounded timing inaccuracy on master compared to 3.10.3 #2420 reproduction → 2500 ms ± 10 ms
    5. NetworkDetector promoted to src/platforms/esp/32/util/
    6. Teensy / bare-metal targets retain current behavior in Phases 1+2 (spin tier + N=1 waitDone flag-poll); no regression.

    Phase 3 (Option A or B) unlocks the multi-driver concurrent case on ESP32. Phase 4 is the long-term architectural payoff across all platforms.

    Future / orthogonal work

    Sub-issues

    Implementation tracked separately:

  2. zackees commented on Jun 5, 2026

    @zackees
    MemberAuthor

    Status update: Phase 1 + Phase 2 merged

    Both phases of the rollout from this umbrella have landed on master:

    Phase PR Issue What landed
    Phase 1 #2827 #2818 (closed) Tier-2 microsecond spin in waitForCondition, public FastLED.setWaitSpinBudgetUs(N) setter (default 250 us). Combined with the already-merged #2817, the wait now does instant -> spin -> NetworkDetector-gated yield.
    Phase 2 #2828 #2819 (closed) IChannelDriver::waitDone(u32 timeoutMs) virtual with default-delegate to waitForReady, manager-side N=1 fast path in ChannelManager::waitForReady. Drivers can now override waitDone to block directly on their ISR-driven completion primitive.

    What's still on the table

    This umbrella stays open to track the remaining strategic items from the synthesis comment above:

    • Phase 3 (ESP32 / FreeRTOS only) - shared-sem/poll-verify or task-notification fan-in for the N>1 multi-driver aggregate wait. Currently those waits still go through the tiered loop; works correctly but doesn't get the ISR-exact wakeup.
    • Phase 4 (long-term, opt-in via FastLED.setAsyncShow(true)) - decoupled async show() so loop() compute overlaps with the previous frame's DMA.
    • Per-driver waitDone() overrides - the Phase 2 fast path only fires when drivers opt in by overriding waitDone(). Each one is a thin wrapper over the driver's existing semaphore-backed wait. Recommended order: PARLIO -> RMT5 -> LCD_SPI -> I2S_SPI -> SPI clockless -> I2S LCD_CAM (~20 LOC) -> LCD_RGB (~20 LOC) -> Teensy ObjectFLED/FlexIO flag-poll. Each can land as a small individual PR.

    Effect on the original #2420 reporter

    For the 35-LED WS2812B sketch with no WiFi.begin():

    The drift originally reported in #2420 should now be substantially reduced even before any driver-side overrides land.

  3. zackees commented on Jun 6, 2026

    @zackees
    MemberAuthor

    Closing #2815

    All actionable work tracked under this umbrella is merged to master:

    PR Issue Status What landed
    #2817 -- MERGED Track 2 - runtime fl::NetworkDetector::isAnyNetworkActive() gating in waitForCondition, replacing the compile-time #if defined(FL_IS_ESP_32P4) carve-out.
    #2827 #2818 (closed) MERGED Phase 1 - Tier 1 instant check + Tier 2 bounded microsecond spin (FASTLED_WAIT_SPIN_BUDGET_US, default 250 us). Public FastLED.setWaitSpinBudgetUs(N) / FastLED.getWaitSpinBudgetUs() setters on CFastLED.
    #2828 #2819 (closed) MERGED Phase 2 - IChannelDriver::waitDone(u32 timeoutMs) virtual with default-delegate to waitForReady; manager-side N=1 fast path in ChannelManager::waitForReady that delegates directly to driver->waitDone(timeoutMs) when exactly one driver is BUSY.
    #2829 -- MERGED Lint follow-up: move the fl/net/network_detector.h stub into namespace fl::net (back-compat using alias preserves fl::NetworkDetector for existing consumers).

    The combined wait now does instant check -> 250 us spin -> NetworkDetector-gated cooperator yield -> per-driver waitDone() (when overridden). For the original #2420 reporter's 35-LED WS2812B sketch with no WiFi.begin(), the vTaskDelay(>=1 tick) floor that drove the timing drift is gone, and the drift around the ~1.05 ms transmit boundary collapses into the 250 us Tier-2 spin.

    What remains as separate, smaller scope (not blocking this issue)

    The umbrella's strategy synthesis listed two future-scope tracks. Neither should keep #2815 open since they are clearly delimited follow-up work and not necessary to call this umbrella complete:

    • Per-driver waitDone() overrides - each driver wraps its existing semaphore-backed wait (PARLIO -> parlio_tx_unit_wait_all_done, RMT5 -> rmt_tx_wait_all_done, LCD_SPI / I2S_SPI -> existing xSemaphoreTake(mCompleteSem), etc.). Each one is a thin wrapper that can land as its own small PR; the Phase 2 default-delegate ensures no regression for unmigrated drivers.
    • Phase 3 N>1 fan-in (ESP32 / FreeRTOS only) - shared-sem-with-poll()-verify or xTaskNotifyIndexedFromISR bitmask for multi-driver aggregate waits. Today multi-driver waits fall through to the tiered loop; correct but not ISR-exact.
    • Phase 4 decoupled async show() - long-term, behind FastLED.setAsyncShow(true). Architectural shift.

    Each of those is a fresh issue / PR when someone picks it up; they are not part of the original "replace the >=1 tick busy-sleep" goal that this umbrella captures.

    Closing as resolved.

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