Skip to content

Port RmtMemoryManager to RMT4 — WiFi-resistant TX + central TX/RX ledger for classic ESP32 #3469

Closed

Description

@zackees

Goal

Bring classic-ESP32 / esp32dev (RMT4, IDF 4.x) up to the RMT5 stability profile under network interference by porting the RmtMemoryManager central allocation ledger + adaptive buffer-block strategy. Today RMT4 relies on a reactive underflow detector (skip pixels when the ISR misses its refill deadline); RMT5 uses a proactive allocator that triple-buffers when NetworkStateTracker::isActive() reports WiFi activity. The proactive path visibly reduces glitches during simultaneous WiFi + LED output.

Depends on #3461 (IRMT4Peripheral wrapper) and #3467 (RX driver backport) — both merged. Follows the same rmt_4 vs rmt_5 split precedent the wrapper + RX PRs used.

Survey of the current state

What RmtMemoryManager actually is

A centralised memory-allocation ledger that tracks on-chip RMT symbol memory consumed by TX and RX channels, with separate accounting for two platform architectures:

  • Global pool — classic ESP32 / S2, 512 or 256 words shared across all 8 or 4 channels.
  • Dedicated TX/RX pools — ESP32-S3 / C3 / C6 / H2.

It enforces a double-buffer policy for TX channels (2× SOC_RMT_MEM_WORDS_PER_CHANNEL), adaptively demotes to 1× on memory-tight chips (ESP32-C3/C6/H2 with only ~96 total words), and promotes to 3× when the networkActive flag is set — the proactive triple-buffering trick.

Key files (all in src/platforms/esp/32/drivers/rmt/rmt_5/):

  • rmt_memory_manager.h (lines 96-468) — public API: allocateTx, allocateRx, tryAllocateTx, tryAllocateRx, free, hasActiveRxChannels, isDMAAvailable, allocateDMA, freeDMA.
  • rmt_memory_manager.cpp.hpp (lines 32-303) — MemoryLedger struct, calculateMemoryBlocks() adaptive logic.
  • channel_driver_rmt.cpp.hpp (lines 617-698) — RMT5 TX allocation flow.
  • network_state_tracker.h (lines 39-78) — singleton the TX driver polls for the networkActive flag.

RX pre-registers at construction time (line 564 of the pre-#3467 rmt_rx_channel.cpp.hpp, now rmt_rx_5/rmt_rx_channel_5.cpp.hpp) so any subsequent TX enrollment can see RX is live and adjust.

How RMT4 handles the same problem today

Reactive underflow detection. src/platforms/esp/32/drivers/rmt/rmt_4/channel_driver_rmt4.h:374-389:

void fillNextBuffer(ChannelState* state, bool checkTime) {
    u32 now = __clock_cycles();
    if (checkTime && state->lastFill != 0) {
        i32 delta = static_cast<i32>(now - state->lastFill);
        if (delta > static_cast<i32>(state->maxCyclesPerFill)) {
            // Too much time elapsed - WiFi interrupt interference detected
            state->pixelDataPos = state->pixelDataSize;
        }
    }
    state->lastFill = now;
    // …fill the buffer half…
}

If the ISR is late by more than maxCyclesPerFill (calculated once at channel init and never revisited), the current pixel stream is truncated — the strip shows a visible glitch. That's the entire WiFi-robustness story on RMT4 today. FASTLED_RMT_MEM_BLOCKS is fixed at 2 for the lifetime of the channel; no allocation manager exists.

What porting the manager to RMT4 buys us

  1. Proactive triple-buffering when network is active. When NetworkStateTracker::isActive() returns true, calculateMemoryBlocks() returns 3 instead of 2, and TX gets 3× 64 = 192 symbol slots per channel to absorb refill jitter. Directly reduces the frequency of delta > maxCyclesPerFill events — the ISR has more headroom, so it's less likely to miss the refill deadline in the first place.

  2. Central accounting for TX + RX coexistence. The RX driver we just landed in feat(rmt_rx): backport RmtRxChannel to IDF 4.x (#3465) #3467 (rmt_rx_4/rmt_rx_channel_4.cpp.hpp) allocates a channel from a descending pool so it doesn't collide with the TX ascending pool. But the accounting is per-driver — the TX driver doesn't know RX is holding channel 7. With a central ledger, TX enrollment can see hasActiveRxChannels() and route around it explicitly.

  3. Deterministic failure semantics. Right now if configureChannel() fails inside rmt_config() because we somehow exhausted the SOC-managed memory, the failure mode is silent (rmt_config returns ESP_ERR_NO_MEM, we log and continue). With a central ledger the failure surfaces at the tryAllocateTx() call site with RmtMemoryError::OUT_OF_MEMORY, and the caller can fall back to 1× buffering (handleAllocateTxFailure() cold path).

Plan

Phase 1 — Move the manager under rmt/rmt_4/ and split the shared surface

Two RMT peripheral drivers now both need it. The type itself is largely IDF-agnostic (it's a bookkeeper, not a hardware driver), but a naive shared file would sit in an awkward location. Options:

  • Option A (recommended): git mv rmt/rmt_5/rmt_memory_manager.{h,cpp.hpp} into rmt/rmt_memory_manager_5.{h,cpp.hpp} at the parent level, add rmt/rmt_memory_manager_4.{h,cpp.hpp} for the RMT4 variant. Two files, two impls, both included by their respective rmt_4/_build.cpp.hpp / rmt_5/_build.cpp.hpp.
  • Option B: Keep them separate under rmt_4/ and rmt_5/ — mirror the wrapper / RX split precedent exactly.

Option B is more consistent with what the wrapper and RX PRs did. Recommend Option B.

Final layout:

src/platforms/esp/32/drivers/rmt/
├── rmt_4/
│   ├── rmt_memory_manager_4.h              -- NEW
│   ├── rmt_memory_manager_4.cpp.hpp        -- NEW
│   ├── network_state_tracker_4.{h,cpp.hpp} -- NEW (or shim to rmt_5's)
│   ├── channel_driver_rmt4.{h,cpp.hpp}     -- edited to call the manager
│   └── …
└── rmt_5/
    ├── rmt_memory_manager.{h,cpp.hpp}      -- unchanged
    ├── network_state_tracker.{h,cpp.hpp}   -- unchanged
    └── …

Phase 2 — Port RmtMemoryManager to RMT4

Copy the RMT5 impl with explicit deletions for the DMA paths (RMT4 has no DMA):

Keep:

  • MemoryLedger struct + singleton pattern
  • allocateTx(channel_id, /*use_dma=*/false, networkActive) — pass use_dma=false unconditionally (RMT4 never has DMA)
  • allocateRx(channel_id, symbols, /*use_dma=*/false)
  • tryAllocate* status-code variants
  • free(channel_id, is_tx)
  • hasActiveRxChannels()
  • calculateMemoryBlocks(networkActive, ...) — the adaptive 2×/3× logic
  • Reservation API for external (non-FastLED) RMT usage

Delete:

  • isDMAAvailable(), allocateDMA(), freeDMA() and their storage
  • The ESP32-S3-specific TX/RX DMA-conflict fork
  • Any use_dma conditional in calculateMemoryBlocks() (the "with-DMA channels get 1×" branch)

Pool geometry for the ledger's initPlatformLimits():

  • Classic ESP32 (FL_IS_ESP_32DEV): 8 channels × 64 words = 512 words, global pool.
  • ESP32-S2 (FL_IS_ESP_32S2): 4 channels × 64 words = 256 words, global pool.

Phase 3 — Port NetworkStateTracker to RMT4

The tracker is IDF-agnostic — it polls esp_wifi_get_mode() and inspects esp_wifi_sta_get_ap_info() for RSSI activity. Both APIs exist on IDF 4.x. Simplest port: git cp the source into rmt_4/network_state_tracker_4.{h,cpp.hpp} behind the same singleton pattern, or (cleaner) leave it in rmt_5/ and change the #include gate so IDF 4 builds can also link it. The source doesn't reference any IDF-5-specific type.

Phase 4 — Wire the manager into ChannelEngineRMT4Impl

Three edit sites in rmt_4/channel_driver_rmt4.cpp.hpp:

  1. ChannelEngineRMT4Impl::configureChannel(state, pin, timing) — before mPeripheral->configureChannel(cfg), call RmtMemoryManager4::instance().tryAllocateTx(mChannelId, networkActive, out_words). If failed, run the cold-path 1× fallback (halve FASTLED_RMT_MEM_BLOCKS, retry). If still failed, return false.

  2. ChannelEngineRMT4Impl::releaseChannel(state) — before the peripheral teardown, call RmtMemoryManager4::instance().free(state->channel, /*is_tx=*/true).

  3. ChannelEngineRMT4Impl::fillNextBuffer(state, checkTime) — the existing reactive check stays. It's a belt-and-braces safety net; the proactive triple-buffering reduces the rate of ISR misses but not to zero. The two mechanisms complement each other.

Phase 5 — Wire the manager into the RX driver

Edit rmt_rx/rmt_rx_4/rmt_rx_channel_4.cpp.hpp (recently added in #3467):

  • In RmtRxChannelImpl constructor, pre-register a minimum RX allocation: RmtMemoryManager4::instance().tryAllocateRx(/*channel_id=*/128 + (pin & 0x7F), /*symbols=*/64, /*use_dma=*/false, alloc_words). Same channel-id convention as the RMT5 sibling (line 560 pre-feat(rmt_rx): backport RmtRxChannel to IDF 4.x (#3465) #3467) to avoid TX collision.
  • In destructor, RmtMemoryManager4::instance().free(mMemoryChannelId, /*is_tx=*/false).
  • In begin(), if the buffer size changes on re-init, free() and re-allocate.

Phase 6 — Tests

  • Host tests — the manager is IDF-agnostic; add unit tests in tests/platforms/shared/mock/esp/32/drivers/rmt_memory_manager_4.cpp covering: exhaustion, network-active bump, per-channel free, hasActiveRxChannels() state, reservation API. Follows the same pattern as the Rmt4PeripheralMock tests (test(rmt4): Rmt4PeripheralMock + 22 host unit tests, no threads (#3462) #3463).
  • On-device — after the fbuild Windows compile blocker clears, run bash autoresearch on the WROOM with WiFi mode enabled from the RPC. Expected: with the port in place, the underflow rate (glitch events) drops noticeably during simulated WiFi bursts.

Out of scope

  • DMA support for RMT4. Classic ESP32 RMT has no DMA; not a thing to add. The RMT5 manager's DMA slot code is deleted, not ported.
  • ESP32-S3 TX+RX DMA-conflict detection. S3 runs on RMT5, not this driver.
  • Refactoring the NetworkStateTracker to be shared between rmt_4 and rmt_5 in a single location. Nice-to-have; not required. Either git cp or #include from the sibling directory is fine.
  • Peripheral wrapper mock updates. Rmt4PeripheralMock (from test(rmt4): Rmt4PeripheralMock + 22 host unit tests, no threads (#3462) #3463) doesn't need to change — the memory manager is a separate layer above the peripheral.
  • Backporting the RMT5-style handleAllocateTxFailure() cold-path recovery verbatim if the RMT4 driver's failure path can be simpler. Keep the port pragmatic.

Acceptance

  • src/platforms/esp/32/drivers/rmt/rmt_4/rmt_memory_manager_4.{h,cpp.hpp} exist with the ported ledger.
  • ChannelEngineRMT4Impl::{configureChannel,releaseChannel} route allocations through the manager; failure semantics documented in the file docblock.
  • rmt_rx/rmt_rx_4/rmt_rx_channel_4.cpp.hpp pre-registers RX in the manager at construction; frees at teardown.
  • NetworkStateTracker is reachable from the RMT4 driver (either ported or shared).
  • bash test --cpp — host suite stays green, new memory-manager unit tests pass.
  • bash compile esp32dev --examples AutoResearch succeeds (once fbuild Windows blocker clears — CI on Linux exercises this).
  • NetworkStateTracker::isActive() == true → observably lower glitch rate during simultaneous WiFi + LED transmission on the WROOM. Documented in the PR description with before/after numbers if measurable.

Plan drafted with assistance from Claude Code.

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