Skip to content

feat(rmt_rx): backport RmtRxChannel to IDF 4.x (#3465) - #3467

Merged
zackees merged 1 commit into
masterfrom
feat/3465-rmt-rx-idf4-backport
Jul 1, 2026
Merged

zackees merged 1 commit into
masterfrom
feat/3465-rmt-rx-idf4-backport

Conversation

@zackees

@zackees zackees commented Jul 1, 2026 •

Copy link
Copy Markdown
Member

Summary

Closes the long-standing gap where FastLED.addRx(RxBackend::PLATFORM_DEFAULT) on classic ESP32 (esp32dev / IDF 4.x) returned nullptr from the factory and got wrapped as a DummyRxDevice. Every begin() / wait() / decode() was a silent no-op. AutoResearch loopback validation on the WROOM was effectively unsupported.

Mirrors the TX-side rmt_4 vs rmt_5 split exactly, one level deeper:

src/platforms/esp/32/drivers/rmt_rx/
├── rmt_rx_channel.h               -- public interface (unchanged)
├── _build.cpp.hpp                 -- dispatches to two sub-aggregators
├── rmt_rx_5/
│   ├── _build.cpp.hpp             -- NEW
│   └── rmt_rx_channel_5.cpp.hpp   -- git mv'd from old rmt_rx_channel.cpp.hpp
│                                     (IDF 5 impl unchanged; trailing
│                                     "requires RMT5" nullptr stub deleted)
└── rmt_rx_4/
    ├── _build.cpp.hpp             -- NEW
    └── rmt_rx_channel_4.cpp.hpp   -- NEW, IDF 4.x impl

Closes #3465.

IDF 4.x impl highlights

Uses the legacy driver/rmt.h:

  • rmt_config() with rmt_mode = RMT_MODE_RX + rmt_rx_config_t { idle_threshold, filter_ticks_thresh, filter_en }.
  • rmt_driver_install(channel, rx_buf_bytes, 0) — non-zero rx_buf_bytes so the IDF allocates the FreeRTOS ring buffer for us.
  • rmt_get_ringbuf_handle() once at install time, then xRingbufferReceive + vRingbufferReturnItem in wait().
  • rmt_set_gpio() on IDF ≥ 4.4, rmt_set_pin() on older 4.x — same fork the rmt_4 TX driver already has.

No custom IRAM ISR. RX has no latency pressure so the IDF ring buffer is the right primitive — sidesteps the RMT.int_st.val plumbing the TX side needs. Keeps the impl ~440 LoC vs ~1620 for the IDF 5 sibling.

Channel allocation

New IDF-4 RX pool descends from kRmt4RxMaxChannels - 1 (7 on classic ESP32, 3 on ESP32-S2) so TX (which ascends from 0) and RX don't collide on a typical 1-TX + 1-RX AutoResearch setup. Pool size is SOC_RMT_TX_CANDIDATES_PER_GROUP on IDF ≥ 4.4, hardcoded fallback for older IDF.

Decode helpers — duplicated, called out explicitly

The four bit-decoding helpers (isResetPulse / isGapPulse / decodeBit / decodeRmtSymbols) are mirrored from the IDF 5 impl. IDF 5 uses rmt_symbol_word_t (from driver/rmt_rx.h), IDF 4 uses rmt_item32_t (from driver/rmt.h) — same 32-bit field layout, so the algorithm is line-for-line the same, only the cast target differs. Factoring these into a shared backend-agnostic helper is a sensible follow-up and is called out in the file docblock; keeping it out of this PR keeps the diff focused.

Test plan

  • bash test --cpp — host suite 342/342 pass. The new IDF-4 TU is gated on FL_IS_ESP32 && !FASTLED_RMT5, so it doesn't compile on the stub host at all — host coverage is exactly unchanged.
  • clang-format --dry-run --Werror clean on all four new + edited files.
  • bash compile esp32dev --examples AutoResearch — currently blocked on my Windows box by the pre-existing fbuild spec-file backslash regression (cc1plus: fatal error: C:Usersniteris.fbuild...) that also reproduces on plain master. Not introduced by this PR. CI on Linux will exercise the cross-compile.
  • WROOM live validation (jumper-wire AutoResearch loopback decoding a WS2812B / SK6812 capture) rides on the same fbuild blocker and is the final acceptance step — tracked as follow-up work once the fbuild Windows issue is resolved.
  • IDF 5 RX path on S3 / C3 / C6 / H2 / P4 emits identical code — the file was git mv'd, no semantic change.

Out of scope

🤖 Generated with Claude Code

Summary by CodeRabbit

  • New Features

    • Added support for ESP32 RMT RX on both IDF 4.x and IDF 5.x builds.
    • Improved RX handling on classic ESP32/ESP32-S2, including raw edge capture, edge injection, and more reliable decoding.
  • Bug Fixes

    • Fixed build-time confusion between IDF 4 and IDF 5 paths by separating the implementations cleanly.
    • Removed a fallback stub so the correct RX implementation is selected for each platform.
  • Documentation

    • Updated notes to explain the IDF 4 vs IDF 5 split and how the compile-time selection works.

Closes the long-standing gap where `FastLED.addRx(RxBackend::
PLATFORM_DEFAULT)` on classic ESP32 (esp32dev / IDF 4.x) returned
a `nullptr` from the factory and got wrapped as a `DummyRxDevice`
where every `begin()` / `wait()` / `decode()` was a no-op.

Mirrors the TX-side rmt_4 vs rmt_5 split exactly:

  src/platforms/esp/32/drivers/rmt_rx/
  ├── rmt_rx_channel.h               -- public interface (unchanged)
  ├── _build.cpp.hpp                 -- now dispatches to two sub-aggregators
  ├── rmt_rx_5/
  │   ├── _build.cpp.hpp             -- NEW (single include)
  │   └── rmt_rx_channel_5.cpp.hpp   -- git mv'd from old location, IDF 5
  │                                     impl unchanged. The trailing
  │                                     "RmtRxChannel needs RMT5" stub is
  │                                     deleted — replaced by the new IDF 4
  │                                     impl below.
  └── rmt_rx_4/
      ├── _build.cpp.hpp             -- NEW
      └── rmt_rx_channel_4.cpp.hpp   -- NEW, the IDF 4 impl

## IDF 4.x implementation

Uses the legacy `driver/rmt.h` surface:

  - `rmt_config()` with `rmt_mode = RMT_MODE_RX` and an
    `rmt_rx_config_t { idle_threshold, filter_ticks_thresh,
    filter_en }` field.
  - `rmt_driver_install(channel, rx_buf_bytes, intr_flags)` with a
    non-zero `rx_buf_bytes` so the IDF allocates the FreeRTOS ring
    buffer for us.
  - `rmt_get_ringbuf_handle()` once at install time, then
    `xRingbufferReceive()` + `vRingbufferReturnItem()` in `wait()`
    to pop captured `rmt_item32_t*` chunks.
  - `rmt_set_gpio(invert=false)` on IDF >= 4.4, `rmt_set_pin()` on
    older 4.x — same fork the rmt_4 TX driver already uses.

**No custom IRAM ISR.** Unlike the TX path (which needs ISR-driven
double-buffer refill because the RMT TX FIFO is 64 symbols), RX has
no latency pressure — the IDF ring buffer absorbs symbols and the
consumer thread drains them on demand. This keeps the impl small
(~440 LoC, vs ~1620 for the IDF 5 path which has DMA + encoder +
event-callback plumbing).

## Channel allocation

The IDF 4 path now has its own RX channel pool. Allocator descends
from `kRmt4RxMaxChannels - 1` (3 on S2, 7 on classic ESP32) so TX
(which ascends from 0) and RX don't collide on a typical 1-TX+1-RX
AutoResearch setup. The pool size is `SOC_RMT_TX_CANDIDATES_PER_GROUP`
on IDF >= 4.4, or 4/8 hardcoded for older IDF on S2 vs classic ESP32.

## Decode helpers — duplicated, deliberately

The four bit-decoding helpers (`isResetPulse`, `isGapPulse`,
`decodeBit`, `decodeRmtSymbols`) are mirrored from the IDF 5 impl's
anonymous-namespace helpers. The IDF 5 version uses
`rmt_symbol_word_t` (from `driver/rmt_rx.h`); the IDF 4 version
below uses `rmt_item32_t` (from `driver/rmt.h`). Both types have
identical 32-bit field layout (duration0:15 / level0:1 /
duration1:15 / level1:1), so the algorithm is line-for-line the
same — only the cast target differs.

Factoring the helpers into a single backend-agnostic file (using a
portable 32-bit struct + manual bit-mask extraction, no IDF type
dependency) is a clean follow-up. Not landing it in this PR keeps
the diff focused on the gating + IDF 4 impl.

## Validation

- `bash test --cpp` — host suite 342/342 pass. The new IDF-4
  TU is gated against host (its outer `#ifdef FL_IS_ESP32` plus
  `#if !FASTLED_RMT5` skip the file entirely on stub builds), so
  the host-side coverage is exactly unchanged.
- `clang-format --dry-run --Werror` clean on all four new + edited
  files.
- `bash compile esp32dev` is blocked on this Windows host by a
  separate pre-existing fbuild spec-file backslash regression
  (`cc1plus: fatal error: C:Usersniteris.fbuild...`) that also
  reproduces on plain master. **Not introduced by this PR.** CI on
  Linux will exercise the cross-compile. WROOM on-device validation
  (jumper-wire AutoResearch loopback decoding a WS2812B / SK6812
  capture) is the final acceptance step and rides on the same
  blocker; tracked separately.
- The IDF 5 RX impl on S3 / C3 / C6 / H2 / P4 emits identical
  code — the file was `git mv`'d, no semantic change.

Closes #3465.

Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>
@coderabbitai

coderabbitai Bot commented Jul 1, 2026 •

Copy link
Copy Markdown

Review Change Stack

📝 Walkthrough

Walkthrough

Splits the ESP32 RMT RX driver into separate rmt_rx_4 (IDF 4.x) and rmt_rx_5 (IDF 5.x) subdirectories with dedicated unity-build headers. Adds a new ~585-line IDF 4.x implementation of RmtRxChannel using the legacy driver/rmt.h API. Removes the old nullptr-returning stub from the IDF 5.x file and updates README documentation.

Changes

RMT RX IDF 4/5 split

Layer / File(s) Summary
Unity build dispatcher
src/platforms/esp/32/drivers/rmt_rx/_build.cpp.hpp, rmt_rx_4/_build.cpp.hpp, rmt_rx_5/_build.cpp.hpp
Top-level header now includes both rmt_rx_4/_build.cpp.hpp and rmt_rx_5/_build.cpp.hpp; each new sub-header includes its respective implementation file, documenting mutual exclusivity via FASTLED_RMT5.
IDF 4.x RmtRxChannel implementation
rmt_rx_4/rmt_rx_channel_4.cpp.hpp
New file implementing decode helpers for rmt_item32_t symbols, a highest-channel-first allocator, RmtRxChannelImpl with begin()/wait()/decode()/getRawEdgeTimes()/injectEdges()/teardown(), and the create(int pin) factory, gated for classic ESP32/S2 IDF 4.x builds.
IDF 5.x stub removal & docs
rmt_rx_5/rmt_rx_channel_5.cpp.hpp, README.md
Removes the !FASTLED_RMT5 stub that returned nullptr, replaced with a comment referencing the rmt_rx_4 implementation; README updated to describe the IDF 4/5 split.

Sequence Diagram(s)

sequenceDiagram
  participant Caller
  participant RmtRxChannelImpl
  participant RmtRingBuffer
  participant DecodeRmtSymbols

  Caller->>RmtRxChannelImpl: create(pin)
  RmtRxChannelImpl->>RmtRxChannelImpl: begin() - configure, install driver, start RX
  Caller->>RmtRxChannelImpl: wait(timeout_ms)
  RmtRxChannelImpl->>RmtRingBuffer: xRingbufferReceive(timeout)
  RmtRingBuffer-->>RmtRxChannelImpl: rmt_item32_t symbols
  Caller->>RmtRxChannelImpl: decode(timing, out)
  RmtRxChannelImpl->>DecodeRmtSymbols: decodeRmtSymbols(symbols)
  DecodeRmtSymbols-->>RmtRxChannelImpl: decoded bytes or error
  RmtRxChannelImpl-->>Caller: result
Loading

Estimated code review effort

🎯 4 (Complex) | ⏱️ ~60 minutes

Possibly related PRs

  • FastLED/FastLED#3229: Both changes are governed by the FASTLED_RMT5 compile-time flag controlling RMT4 vs RMT5 code path selection on ESP32.

Poem

A rabbit hopped through IDF trees,
Split the RX path with graceful ease—
Four and Five, each in their den,
No more stubs returning null again.
🐇✨ Symbols decoded, ring buffers spin,
Classic ESP32 now lets the signals in!

🚥 Pre-merge checks | ✅ 5
✅ Passed checks (5 passed)
Check name Status Explanation
Description Check ✅ Passed Check skipped - CodeRabbit’s high-level summary is enabled.
Title check ✅ Passed The title clearly describes the main change: backporting RmtRxChannel to IDF 4.x.
Linked Issues check ✅ Passed The changes match the issue: they add a real IDF 4.x RX implementation and split the build into rmt_rx_4 and rmt_rx_5.
Out of Scope Changes check ✅ Passed The PR stays focused on the RX backport and build split; no unrelated code changes are evident.
Docstring Coverage ✅ Passed No functions found in the changed files to evaluate docstring coverage. Skipping docstring coverage check.
✨ Finishing Touches
📝 Generate docstrings
  • Create stacked PR
  • Commit on current branch
🧪 Generate unit tests (beta)
  • Create PR with unit tests
  • Commit unit tests in branch feat/3465-rmt-rx-idf4-backport

Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

❤️ Share

Comment @coderabbitai help to get the list of available commands.

@zackees
zackees merged commit 78b2c7b into master Jul 1, 2026
6 of 9 checks passed
@fastled-project-sync fastled-project-sync Bot moved this from Triage to Done in FastLED Tracker Jul 1, 2026

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 4

🤖 Prompt for all review comments with AI agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

Inline comments:
In `@src/platforms/esp/32/drivers/rmt_rx/rmt_rx_4/rmt_rx_channel_4.cpp.hpp`:
- Around line 82-90: The new RX logging toggle is using a freshly introduced
FASTLED_* macro, which violates the macro naming policy for new config flags.
Rename the guard in rmt_rx_channel_4.cpp.hpp to a non-FASTLED identifier and
update the FL_LOG_RX conditional to use that new symbol, keeping the existing
behavior while avoiding any new public FASTLED_* vocabulary.
- Around line 388-402: `finished()` on `RmtRxChannel4` never becomes true after
a successful `begin()` because `mRunning` is not cleared on the `wait()`
completion paths. Update the `wait()` flow in `RmtRxChannel4::wait` so the
success, timeout, and overflow exits all transition the channel state out of
running (or otherwise set the completion state that `finished()` checks), and
keep `finished()` aligned with that state so polling callers don’t spin forever
after data has already been returned.
- Around line 295-306: `RMT_RX_Channel_4::open` is keeping the requested
`config.hz` in `mResolutionHz` even after `clk_div` is clamped/quantized, so
later conversions in `decode()`, `getRawEdgeTimes()`, and `injectEdges()` use
the wrong tick duration. Update the channel setup to store the realized RMT
clock derived from `kApbHz / clk_div` (after clamping) rather than the raw
requested value, and keep the existing divider calculation as the source of
truth for the actual resolution.
- Around line 573-578: RmtRxChannel::create currently uses a bare new for
RmtRxChannelImpl, which triggers BareAllocationChecker and fails CI. Replace the
direct allocation with fl::make_shared<RmtRxChannelImpl>(pin) while keeping the
negative-pin guard and return type unchanged, so the function still returns
fl::shared_ptr<RmtRxChannel> without a raw allocation hop.
🪄 Autofix (Beta)

Fix all unresolved CodeRabbit comments on this PR:

  • Push a commit to this branch (recommended)
  • Create a new PR with the fixes

ℹ️ Review info
⚙️ Run configuration

Configuration used: Path: .coderabbit.yaml

Review profile: CHILL

Plan: Pro

Run ID: c0c8c47b-9e10-4b1c-8b85-3bceea480ae8

📥 Commits

Reviewing files that changed from the base of the PR and between 5eddaa9 and 1cf7135.

📒 Files selected for processing (6)
  • src/platforms/esp/32/drivers/rmt_rx/README.md
  • src/platforms/esp/32/drivers/rmt_rx/_build.cpp.hpp
  • src/platforms/esp/32/drivers/rmt_rx/rmt_rx_4/_build.cpp.hpp
  • src/platforms/esp/32/drivers/rmt_rx/rmt_rx_4/rmt_rx_channel_4.cpp.hpp
  • src/platforms/esp/32/drivers/rmt_rx/rmt_rx_5/_build.cpp.hpp
  • src/platforms/esp/32/drivers/rmt_rx/rmt_rx_5/rmt_rx_channel_5.cpp.hpp

Comment on lines +82 to +90
#ifndef FASTLED_RX_LOG_ENABLED
#define FASTLED_RX_LOG_ENABLED 0
#endif

#if FASTLED_RX_LOG_ENABLED
#define FL_LOG_RX(X) FL_DBG(X)
#else
#define FL_LOG_RX(X) FL_DBG_NO_OP(X)
#endif

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

📐 Maintainability & Code Quality | 🟠 Major | ⚡ Quick win

Rename the new logging flag out of the frozen FASTLED_* namespace.

Line 82 introduces FASTLED_RX_LOG_ENABLED, which is a brand-new FASTLED_* macro under src/. That violates the repo’s macro policy for new config/capability names and will create the wrong public vocabulary if other files start keying off it. As per path instructions, “Any newly introduced #define ... whose identifier starts with FASTLED_ is a violation.”

🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@src/platforms/esp/32/drivers/rmt_rx/rmt_rx_4/rmt_rx_channel_4.cpp.hpp` around
lines 82 - 90, The new RX logging toggle is using a freshly introduced FASTLED_*
macro, which violates the macro naming policy for new config flags. Rename the
guard in rmt_rx_channel_4.cpp.hpp to a non-FASTLED identifier and update the
FL_LOG_RX conditional to use that new symbol, keeping the existing behavior
while avoiding any new public FASTLED_* vocabulary.

Source: Path instructions

Comment on lines +295 to +306
mResolutionHz = (config.hz != 0) ? config.hz : 40000000u; // 40 MHz
mBufferSize = (config.buffer_size != 0) ? config.buffer_size : 1024;

// RMT clock divider so the RMT tick rate matches the requested
// resolution. The APB clock is 80 MHz on classic ESP32 / S2.
// Example: 40 MHz target -> divider = 2 -> 25 ns per tick.
constexpr u32 kApbHz = 80000000u;
u32 clk_div = kApbHz / mResolutionHz;
if (clk_div == 0)
clk_div = 1;
if (clk_div > 255)
clk_div = 255;

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🎯 Functional Correctness | 🟠 Major | ⚡ Quick win

Store the realized RMT clock, not the requested one.

Lines 295-306 quantize/clamp clk_div, but mResolutionHz keeps the original config.hz. For any value above 80 MHz or not an exact divisor of the 80 MHz APB clock, decode(), getRawEdgeTimes(), and injectEdges() will all convert ticks with the wrong ns-per-tick and silently mis-decode captures.

Proposed fix
-        mResolutionHz = (config.hz != 0) ? config.hz : 40000000u; // 40 MHz
+        const u32 requested_hz = (config.hz != 0) ? config.hz : 40000000u; // 40 MHz
         mBufferSize = (config.buffer_size != 0) ? config.buffer_size : 1024;
@@
-        u32 clk_div = kApbHz / mResolutionHz;
+        u32 clk_div = kApbHz / requested_hz;
         if (clk_div == 0)
             clk_div = 1;
         if (clk_div > 255)
             clk_div = 255;
+        mResolutionHz = kApbHz / clk_div;
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
mResolutionHz = (config.hz != 0) ? config.hz : 40000000u; // 40 MHz
mBufferSize = (config.buffer_size != 0) ? config.buffer_size : 1024;
// RMT clock divider so the RMT tick rate matches the requested
// resolution. The APB clock is 80 MHz on classic ESP32 / S2.
// Example: 40 MHz target -> divider = 2 -> 25 ns per tick.
constexpr u32 kApbHz = 80000000u;
u32 clk_div = kApbHz / mResolutionHz;
if (clk_div == 0)
clk_div = 1;
if (clk_div > 255)
clk_div = 255;
const u32 requested_hz = (config.hz != 0) ? config.hz : 40000000u; // 40 MHz
mBufferSize = (config.buffer_size != 0) ? config.buffer_size : 1024;
// RMT clock divider so the RMT tick rate matches the requested
// resolution. The APB clock is 80 MHz on classic ESP32 / S2.
// Example: 40 MHz target -> divider = 2 -> 25 ns per tick.
constexpr u32 kApbHz = 80000000u;
u32 clk_div = kApbHz / requested_hz;
if (clk_div == 0)
clk_div = 1;
if (clk_div > 255)
clk_div = 255;
mResolutionHz = kApbHz / clk_div;
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@src/platforms/esp/32/drivers/rmt_rx/rmt_rx_4/rmt_rx_channel_4.cpp.hpp` around
lines 295 - 306, `RMT_RX_Channel_4::open` is keeping the requested `config.hz`
in `mResolutionHz` even after `clk_div` is clamped/quantized, so later
conversions in `decode()`, `getRawEdgeTimes()`, and `injectEdges()` use the
wrong tick duration. Update the channel setup to store the realized RMT clock
derived from `kApbHz / clk_div` (after clamping) rather than the raw requested
value, and keep the existing divider calculation as the source of truth for the
actual resolution.

Comment on lines +388 to +402
bool finished() const FL_NO_EXCEPT override {
// The legacy IDF 4 driver doesn't expose a direct "done" flag
// the way IDF 5 does. We treat "finished" as "the consumer has
// popped at least one symbol chunk AND the ring buffer is
// empty", which matches AutoResearch's polling-loop usage.
if (!mRunning) {
return true;
}
if (mInternalBuffer.empty()) {
return false;
}
// The ring buffer is opaque from the const path; return based on
// mRunning being cleared by drainRingbuf().
return false;
}

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🎯 Functional Correctness | 🟠 Major | ⚡ Quick win

Completion never transitions this channel back to “finished”.

finished() only returns true when mRunning becomes false, but none of the success/timeout/overflow exits in wait() ever clear that flag. After the first begin(), any caller polling finished() will spin forever even though wait() already returned data.

Also applies to: 404-443

🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@src/platforms/esp/32/drivers/rmt_rx/rmt_rx_4/rmt_rx_channel_4.cpp.hpp` around
lines 388 - 402, `finished()` on `RmtRxChannel4` never becomes true after a
successful `begin()` because `mRunning` is not cleared on the `wait()`
completion paths. Update the `wait()` flow in `RmtRxChannel4::wait` so the
success, timeout, and overflow exits all transition the channel state out of
running (or otherwise set the completion state that `finished()` checks), and
keep `finished()` aligned with that state so polling callers don’t spin forever
after data has already been returned.

Comment on lines +573 to +578
fl::shared_ptr<RmtRxChannel> RmtRxChannel::create(int pin) FL_NO_EXCEPT {
if (pin < 0) {
FL_WARN_F("[RMT4 RX] create() refused: pin %s is negative", pin);
return nullptr;
}
return fl::shared_ptr<RmtRxChannel>(new RmtRxChannelImpl(pin));

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

📐 Maintainability & Code Quality | 🔴 Critical | ⚡ Quick win

Use fl::make_shared here; CI is already failing on the bare allocation.

Line 578 is tripping BareAllocationChecker, so this PR currently fails the macOS unit-test pipeline. fl::make_shared<RmtRxChannelImpl>(pin) fixes the checker and removes the raw allocation hop. As per coding guidelines, “Use proper RAII patterns with smart pointers (fl::shared_ptr, fl::unique_ptr) ... instead of raw pointers.”

Proposed fix
-    return fl::shared_ptr<RmtRxChannel>(new RmtRxChannelImpl(pin));
+    return fl::make_shared<RmtRxChannelImpl>(pin);
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
fl::shared_ptr<RmtRxChannel> RmtRxChannel::create(int pin) FL_NO_EXCEPT {
if (pin < 0) {
FL_WARN_F("[RMT4 RX] create() refused: pin %s is negative", pin);
return nullptr;
}
return fl::shared_ptr<RmtRxChannel>(new RmtRxChannelImpl(pin));
fl::shared_ptr<RmtRxChannel> RmtRxChannel::create(int pin) FL_NO_EXCEPT {
if (pin < 0) {
FL_WARN_F("[RMT4 RX] create() refused: pin %s is negative", pin);
return nullptr;
}
return fl::make_shared<RmtRxChannelImpl>(pin);
🧰 Tools
🪛 GitHub Actions: unit tests macos / 0_test _ build.txt

[error] 578-578: BareAllocationChecker: bare 'new' used. Line 578: "return fl::shared_ptr(new RmtRxChannelImpl(pin));" — Use fl::make_unique()/fl::make_shared() instead of bare 'new', or add '// ok bare allocation' to suppress.

🪛 GitHub Actions: unit tests macos / test _ build

[error] 578-578: BareAllocationChecker: Line 578: bare 'new' used: 'return fl::shared_ptr(new RmtRxChannelImpl(pin));' — Use fl::make_unique() or fl::make_shared() instead of bare 'new', or add '// ok bare allocation' to suppress.

🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@src/platforms/esp/32/drivers/rmt_rx/rmt_rx_4/rmt_rx_channel_4.cpp.hpp` around
lines 573 - 578, RmtRxChannel::create currently uses a bare new for
RmtRxChannelImpl, which triggers BareAllocationChecker and fails CI. Replace the
direct allocation with fl::make_shared<RmtRxChannelImpl>(pin) while keeping the
negative-pin guard and return type unchanged, so the function still returns
fl::shared_ptr<RmtRxChannel> without a raw allocation hop.

Sources: Coding guidelines, Pipeline failures

zackees added a commit that referenced this pull request Jul 1, 2026
#3469) (#3470)

Ports the RMT5 `RmtMemoryManager` accounting ledger + adaptive
buffer-block strategy to the classic-ESP32 / IDF 4.x RMT driver,
following the rmt_4/rmt_5 split precedent from #3461 and #3467.

## What's in

- `rmt/rmt_4/rmt_memory_manager_4.h`   - header-inline class body
- `rmt/rmt_4/rmt_memory_manager_4.cpp.hpp` - platform-default singleton
- `rmt/rmt_4/network_state_tracker_4.{h,cpp.hpp}` - v1 stub returning
  `false`. Follow-up PR wires this to the shared network detector once
  it's lifted out of the FASTLED_RMT5 guard.

The manager tracks:
- Global word-pool (512 words on classic ESP32, 256 on S2 — 8 or 4
  channels × 64 words per block).
- Per-channel allocations (TX or RX distinguished by `is_tx` flag).
- `hasActiveRxChannels()` for TX-side coordination.
- Adaptive `calculateMemoryBlocks(network_active)` that returns 3 when
  the network is active AND the pool has room for the extra 64-word
  block, else 2 (RMT4 historic default).

## What's out (deliberately)

- No DMA accounting: RMT4 hardware has no DMA channel. The RMT5
  manager's DMA slot ledger is not ported.
- No dedicated TX/RX pools: RMT4 is always a global-pool platform.
- Real network detection: `NetworkStateTracker4::isActive()` is a
  stub `return false` for v1. That means today's behaviour is
  bit-for-bit identical to pre-#3469 — the manager plumbing is in
  place, but the driver still allocates 2 mem blocks per TX channel.
  Follow-up PR flips the stub to poll the (shared) network detector.
- No ISR-side refactor: the `PULSES_PER_FILL_RMT4` refill threshold
  stays fixed. Higher `mem_block_num` values in `rmt_config()` give
  the ISR more headroom before it misses its deadline; the reactive
  `checkTime` truncation in `fillNextBuffer` stays as a belt-and-
  braces safety net.

## Wiring

- `ChannelEngineRMT4Impl::configureChannel`: calls the manager's
  free-then-tryAllocateTx idiom. Failure returns false; caller
  (acquireChannel) treats this the same as HW-channel-count-miss and
  defers the strip to the pending queue. Uses
  `calculateMemoryBlocks(network_active)` to fill in
  `Rmt4ChannelConfig::mMemBlocks`.
- `ChannelEngineRMT4Impl::~ChannelEngineRMT4Impl`: releases every
  in-use channel's allocation.
- `rmt_rx_4/RmtRxChannelImpl` constructor: pre-registers a 64-symbol
  RX reservation with channel-id `128 + (pin & 0x7F)` so TX (using
  raw 0..N-1 IDs) never collides.
- `rmt_rx_4/RmtRxChannelImpl` destructor: releases the RX reservation.

## Tests

19 host `FL_TEST_CASE`s in
`tests/platforms/esp/32/drivers/rmt/rmt_4/rmt_memory_manager_4.cpp`,
covering:
  - pool starts empty
  - TX idle allocation = 128 words, network-active = 192 words
  - graceful demotion to 128 when 192 doesn't fit
  - pool-exhausted refusals
  - duplicate-alloc refusals
  - RX symbol-count recording, zero-symbol rejection
  - free() releases correctly; wrong is_tx and unknown-channel misses
  - free-then-realloc reconfigure idiom
  - hasActiveRxChannels tracks RX lifetime, ignores TX
  - calculateMemoryBlocks 2/3 selection + fallback when the extra
    block doesn't fit
  - reset() clears the ledger
  - 4 concurrent TX up to pool limit, 5th refused

Local results:
  - `bash test rmt_memory_manager_4 --cpp --clean`:
      [doctest] test cases: 19 | 19 passed | 0 failed
  - `bash test --cpp`: 342/342 pass (no regression).
  - `clang-format --dry-run --Werror` clean on every touched file.

The manager class body is header-inline on purpose so host tests
build it directly without needing the ESP-IDF headers. Only the
platform-default `instance()` singleton lives in the .cpp.hpp behind
the usual `FL_IS_ESP32 && !FASTLED_RMT5` guard.

`bash compile esp32dev` is still blocked on the pre-existing fbuild
Windows spec-file backslash regression (`cc1plus: fatal error:
C:Usersniteris.fbuild...`) that reproduces on plain master, so
on-device WROOM validation of the network-active bump rides on that
blocker as before. CI on Linux exercises the cross-compile.

Closes #3469.

Co-authored-by: Claude Opus 4.7 (1M context) <[email protected]>
zackees added a commit that referenced this pull request Jul 1, 2026
…3560)

esp32c2 has been red on master since #3467 (feat(rmt_rx): backport
RmtRxChannel to IDF 4.x) with:

    fl.channels+.cpp:(.text._ZN2fl8RxDevice6createILNS_12RxDeviceTypeE2EEENS_10shared_ptrIS0_EEi+0x12):
    undefined reference to `fl::RmtRxChannel::create(int)'

ESP32-C2 has no RMT peripheral (`SOC_RMT_SUPPORTED == 0` →
`FASTLED_ESP32_HAS_RMT == 0`), and platforms/esp/32/feature_flags/
enabled.h forces `FASTLED_RMT5 = 0` for that chip. So neither
rmt_rx_4/'s
`FASTLED_ESP32_HAS_RMT && !FASTLED_ESP32_RMT5_ONLY_PLATFORM && !FASTLED_RMT5`
gate NOR rmt_rx_5/'s `FASTLED_RMT5` gate compiles, and
`RmtRxChannel::create` has no definition to link against.

Mirror the exact gate at the specialisation site: when the SoC
doesn't have RMT silicon, collapse `RxDevice::create<RMT>` to a
DummyRxDevice with a clear failure string ('RMT RX not supported on
this ESP32 SoC') instead of trying to call an unlinkable symbol.
Also #include the feature-flags header up top so the preprocessor
gate resolves.

Verified locally on Windows: `bash compile esp32c2 --examples Blink`
succeeds (2m04s cold, previously died in the ld step).

Co-authored-by: Claude Opus 4.7 (1M context) <[email protected]>
@zackees
zackees deleted the feat/3465-rmt-rx-idf4-backport branch August 21, 2026 19:15
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

Status: Done

Development

Successfully merging this pull request may close these issues.

Backport RmtRxChannel to IDF 4.x — RX device for classic ESP32 (esp32dev)

1 participant