Repository navigation
Description
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:
- 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.
- 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 enterswaitForReady()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_NULLisEthernetActive()—esp_netifinterface enumerationisBluetoothActive()—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);
#endifThis 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
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).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).- 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_32P4carve-out is replaced by the same runtime decision, which on P4 always returns "no radio"). - 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).
NetworkDetectoris promoted out of thermt_5/subdirectory so all wait sites can use it.
Cross-references
- [Bug] Compounded timing inaccuracy on master compared to 3.10.3 #2420 — original timing drift report (target fix)
- ESP32-S3: I2S driver starves websockets, SPI output incorrect, Audio driver FPS impact #2254 — origin of the deep-yield-for-WiFi rationale
- ESP32-P4 PARLIO: FastLED.show() appears to block for ~16.7 ms before WS2812 data burst begins #2493 — PARLIO 16.7 ms show() block, mitigated with the
FL_IS_ESP_32P4carve-out; this issue generalizes that mitigation - FastLED Channels API #2167 — Channels API parent
src/fl/channels/manager.cpp.hpp:364-388— primary wait sitesrc/fl/channels/driver.cpp.hpp:11-35— secondary wait sitesrc/fl/task/executor.cpp.hpp:75-152—task::runandpumpCoroutines(1000)tick floorsrc/platforms/esp/32/drivers/rmt/rmt_5/network_detector.h— runtime radio detector (existing, needs promotion)
Metadata
Metadata
Assignees
Labels
Type
Projects
- StatusShow more project fieldsDone
Activity
zackees commentedon Jun 5, 2026
Design strategy review — 6 strategies investigated, 4-phase rollout
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
poll()-verify (condvar pattern)poll()is the truth — sem is purely a wakeup.bindCompletionSignal(grp, bit)virtualeSetBitssticky, returned mask diagnoses hangssetCompletionNotify(handle, bit)virtualCONFIG_FREERTOS_TASK_NOTIFICATION_ARRAY_ENTRIES=2and reserved index.driver->waitDone(), N>1 fan-in (#1 or #3)waitDone()+ 7 one-line overrides; fan-in mechanism only on drivers that need itexamples/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).show()non-blocking)loop()compute with previous DMAshow(); delay(N)sketches that assume strip-is-idle post-show. Must be behindsetAsyncShow(true)opt-in. Future v2.poll())waitForConditionbodyCross-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.his explicit:acquire()on a depleted sem PANICS (would deadlock — no scheduler to wake you)try_acquire_for(rel_time)ignores the timeout — falls through to non-blockingtry_acquirexSemaphoreCreateCountingCountingSemaphoreTeensy(ISR-safe counter; no wait)Takewith timeoutxSemaphoreTake(ticks)acquire()PANICsxEventGroupSetBitsFromISR/WaitBitsxTaskNotifyIndexedFromISRtask::run(SYSTEM)→vTaskDelayyield()(Arduino — pumps USB serial)yield()__WFE/__WFI+__SEV-from-ISRStrategy-by-strategy translation
yield()instead oftask::run(SYSTEM)— the abstraction already covers this.waitDone()virtual works; Teensy override is a busy-poll on a volatile flag (or__WFEloop). No FreeRTOS dep. Default-delegate to legacywaitForReadypreserves existing Teensy paths.Taketo block; on Teensy that PANICs. Teensy falls back to plain polling — equivalent to Strategy 6 alone.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, novTaskDelay, so the per-poll overhead is already negligible.A future enhancement worth filing separately: add a
__WFE/__SEVbare-metal "block until interrupt" helper insemaphore_teensy.hso 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, anduxMaxCountsaturation. 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:poll()→ loop. Harmless.poll()is truth.uxMaxCountsaturationpoll()is source of truth. Degrades to plain poll, never wrong.waitForReady"steals" GivesStructurally 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. ISRGivemoves the task back to ready; withportYIELD_FROM_ISRit runs on ISR exit. Wakeup latency is ~µs (not the ≥1 ms tick floor ofvTaskDelay).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)Composability
Recommended phased rollout
Spin budget across all phases:
driver->waitDone()→xSemaphoreTake(sem, ticks)— exact, ISR-driven, no spinpoll()-verify (exact, ISR-driven) — no spinThe 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.
ChannelManager::waitForCondition(src/fl/channels/manager.cpp.hpp:364-388) ANDIChannelDriver::waitForCondition(src/fl/channels/driver.cpp.hpp:11-35). Extract a shared helper to avoid drift.FASTLED_WAIT_SPIN_BUDGET_US+ runtimeFastLED.setWaitSpinBudgetUs(N)per Public Settings Pattern).!isAnyNetworkActive(), extend the spin to ~5 ms; deep yield otherwise.NetworkDetectorpromoted fromsrc/platforms/esp/32/drivers/rmt/rmt_5/tosrc/platforms/esp/32/util/. ExistingFL_IS_ESP_32P4carve-out removed — NetworkDetector returns "no radio" on P4 via weak-symbol fallback automatically.waitForConditionwith a synthetic condition; extendexamples/AutoResearch/AutoResearch.inowith a [Bug] Compounded timing inaccuracy on master compared to 3.10.3 #2420-style timing-drift mode runnable viabash autoresearch <board>.Phase 2 — Hybrid N=1 fast-path (separate issue). Cross-platform.
virtual bool IChannelDriver::waitDone(u32 timeoutMs) FL_NOEXCEPTtosrc/fl/channels/driver.h. Default implementation:return waitForReady(timeoutMs);(preserves existing slow loop for any driver that doesn't override).parlio_tx_unit_wait_all_done(parlio_peripheral_esp.cpp.hpp:334)rmt_tx_wait_all_done(rmt5_peripheral_esp.cpp.hpp/ IDF semaphore)xSemaphoreTake(mCompleteSem)(lcd_spi_peripheral_esp.cpp.hpp:452)xSemaphoreTake(mCompleteSem)(i2s_spi_peripheral_esp.cpp.hpp:556)spi_device_get_trans_result(IDF semaphore)waitDoneas a busy-poll on the volatile completion flag they already set in their DMA-done ISR — no FreeRTOS dependency.waitForReady: classify drivers viapoll()pre-pass; if exactly one BUSY, returnthat->waitDone(timeoutMs)directly, bypassing the spin tier entirely.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):
xSemaphoreCreateCounting(kMaxDrivers, 0)(kMaxDrivers = 16is ample).Gives the shared sem in addition to (or instead of) its private one.waitForReadyloop:poll()-verify →xSemaphoreTake(sem, remaining_ticks)→ repeat.Option B — Strategy 3 (task notification with bits, richer diagnostics):
virtual void IChannelDriver::setCompletionNotify(TaskHandle_t, u32 bit) FL_NOEXCEPT {}(no-op default).CONFIG_FREERTOS_TASK_NOTIFICATION_ARRAY_ENTRIES=2toplatforms/esp/32/sdkconfig.defaults; reserve index 1.waitForReadyFanIn: bind notify per BUSY driver, thenxTaskNotifyWaitIndexed(FL_NOTIFY_IDX, 0, ULONG_MAX, &recvd, ticks)in a loop accumulating bits until(acc & expected_mask) == expected_mask.setCompletionNotifyget a capability check + fall back to polling.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.
Phase 4 (future / v2) — Decoupled async show. Cross-platform.
FastLED.setAsyncShow(true)opt-in orFASTLED_SHOW_V2macro.show()becomes "reap + kickoff" — nowaitForReadyin the synchronous path. Reaper runs onfl::task::Scheduler::update().show(); delay(N)assume strip-is-idle post-show).Acceptance criteria (refined)
The Phase 1+2 combination meets the original issue body's acceptance criteria:
FL_IS_ESP_32P4carve-out needed)NetworkDetectorpromoted tosrc/platforms/esp/32/util/waitDoneflag-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
__WFE/__SEVbare-metal block-until-interrupt helper insemaphore_teensy.h— would let Teensy drivers'waitDone()be truly low-power instead of polling. File as a separate enhancement; not on the perf(channels): replace =1 FreeRTOS-tick busy-sleep in waitForReady with ISR-completion + NetworkDetector-gated yield (refs #2420, #2254, #2493) #2815 critical path.Sub-issues
Implementation tracked separately:
waitDone()virtual + per-driver ISR fast pathperf(channels): runtime NetworkDetector-gated yield in waitForConditi…
perf(channels): add waitDone() virtual + manager N=1 fast path (Phase…
Merge pull request #2828 from FastLED/feat/channels-waitdone-2819-v2
zackees commentedon Jun 5, 2026
Status update: Phase 1 + Phase 2 merged
Both phases of the rollout from this umbrella have landed on master:
waitForCondition, publicFastLED.setWaitSpinBudgetUs(N)setter (default 250 us). Combined with the already-merged #2817, the wait now does instant -> spin -> NetworkDetector-gated yield.IChannelDriver::waitDone(u32 timeoutMs)virtual with default-delegate towaitForReady, manager-side N=1 fast path inChannelManager::waitForReady. Drivers can now overridewaitDoneto 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:
FastLED.setAsyncShow(true)) - decoupled asyncshow()soloop()compute overlaps with the previous frame's DMA.waitDone()overrides - the Phase 2 fast path only fires when drivers opt in by overridingwaitDone(). 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():task::run(250, SYSTEM)->vTaskDelay(>=1 tick)floor: eliminated by perf(channels): runtime NetworkDetector-gated yield in waitForCondition (refs #2815) #2817's NetworkDetector gate.waitDone()override, perf(channels): add waitDone() virtual + manager N=1 fast path (Phase 2 of #2815, Closes #2819) #2828's manager fast path will additionally wake on the DMA-done ISR directly, droppingshow()wall time to roughly transmit time + a few microseconds.The drift originally reported in #2420 should now be substantially reduced even before any driver-side overrides land.
perf(channels): add Tier-2 microsecond spin to waitForCondition (Phas…
zackees commentedon Jun 6, 2026
Closing #2815
All actionable work tracked under this umbrella is merged to master:
fl::NetworkDetector::isAnyNetworkActive()gating inwaitForCondition, replacing the compile-time#if defined(FL_IS_ESP_32P4)carve-out.FASTLED_WAIT_SPIN_BUDGET_US, default 250 us). PublicFastLED.setWaitSpinBudgetUs(N)/FastLED.getWaitSpinBudgetUs()setters onCFastLED.IChannelDriver::waitDone(u32 timeoutMs)virtual with default-delegate towaitForReady; manager-side N=1 fast path inChannelManager::waitForReadythat delegates directly todriver->waitDone(timeoutMs)when exactly one driver is BUSY.fl/net/network_detector.hstub intonamespace fl::net(back-compatusingalias preservesfl::NetworkDetectorfor 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 noWiFi.begin(), thevTaskDelay(>=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:
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 -> existingxSemaphoreTake(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.poll()-verify orxTaskNotifyIndexedFromISRbitmask for multi-driver aggregate waits. Today multi-driver waits fall through to the tiered loop; correct but not ISR-exact.show()- long-term, behindFastLED.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.
fix(core): adaptive yield in show()'s refresh throttle (FastLED#3762, f…