Repository navigation
feat(spi,esp32): pre-queue alternate-buffer SPI chunk for >680-LED strips (refs #2304) - #2810
Conversation
…rips (refs #2304) Closes the inter-chunk gap that opens when a long strip (>~680 LEDs) splits into multiple SPI DMA transactions. Today the pipeline queues chunk A, waits, encodes+queues chunk B from poll(). Between A and B the SPI line idles for the host-task latency until poll() notices completion — under RTOS contention that gap can exceed WS2812B's ~50 µs reset threshold and trigger a visible refresh on the strip. What this does: - In `startFirstDma()`, when async-DMA is in use AND the encoded payload exceeds a single staging buffer, pre-encode and pre-queue buffer B right after queuing A. ESP-IDF's SPI driver allows multiple in-flight transactions (`dev_config.queue_size = 4` is already set); the ISR transitions A → B without host involvement. Capped at 2 in flight to keep the pipeline shallow and predictable. - In `advancePipeline()`, the in-flight detector is now `transAInFlight || transBInFlight` (refreshed per iteration) rather than the single `mPipeline.mDmaInFlight` boolean. When one chunk completes and data remains, the just-freed buffer is refilled and re-queued, maintaining 2-in-flight as long as there's payload. - ESP32-C6 split-polling path (`kSpiUsePolling = true`) only allows one in-flight polling transaction at a time, so we keep the existing single-queue behaviour there. C6 still benefits from the encode/wait overlap but cannot get ISR-chained gap-free streaming without an ESP-IDF API change. - `transAInFlight` / `transBInFlight` per-channel booleans track real ESP-IDF state so the completion drain matches whichever transaction reported done; no more guessing which slot fired. Tests (host-side, no ESP-IDF dependency): - `tests/platforms/esp/32/drivers/spi/spi_pingpong_pipeline_logic.cpp` (new, ~305 lines) models the buffer-rotation invariants in plain C++: (1) both A and B queued for long strips in async mode, (2) only A queued for one-chunk strips, (3) refill-on-completion is ping-pong, (4) at most 2 chunks in flight while data remains, (5) final drain waits for both outstanding before marking complete. NOT validated by this PR (deferred to hardware): - On-device byte equality with the old single-queue behaviour. - Inter-chunk timing under RTOS contention (the original symptom). - Both should be exercised via `bash autoresearch --spi` on real ESP32 hardware with a ≥1000-LED WS2812B strip — that's the next iteration. Process note: the agent that drafted this was interrupted mid-stream when its `bash test --clean` rebuild collided with stop-hook lock contention on the same shared build directory. The file deltas above are its pre-interruption work product, verified clean in the worktree; main checkout has been reverted of the leaked untracked test file. Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>
|
No actionable comments were generated in the recent review. 🎉 ℹ️ Recent review info⚙️ Run configurationConfiguration used: Path: .coderabbit.yaml Review profile: CHILL Plan: Pro Run ID: 📒 Files selected for processing (1)
🚧 Files skipped from review as they are similar to previous changes (1)
📝 WalkthroughWalkthroughDriver pre-queues a second DMA transaction in async mode and updates STREAMING logic to track both transA/transB in-flight; a host-side PipelineModel and eight tests validate async vs polling behaviors and the ChangesSPI DMA Ping-Pong Pipeline Enhancement
Sequence DiagramsequenceDiagram
participant Client
participant Pipeline as SPI_Pipeline
participant TransA as Transaction_A
participant TransB as Transaction_B
participant DMA
Client->>Pipeline: startFirstDma()
Pipeline->>Pipeline: encode Chunk A -> stagingA
Pipeline->>TransA: queue transA
Pipeline->>DMA: submit transA
alt async mode && more data
Pipeline->>Pipeline: encode Chunk B -> stagingB
Pipeline->>TransB: queue transB
Pipeline->>DMA: submit transB
Pipeline->>Pipeline: set transBInFlight
end
loop advancePipeline() STREAMING
Client->>Pipeline: stepStreaming()
Pipeline->>Pipeline: anyInFlight = transAInFlight || transBInFlight
alt anyInFlight
Pipeline->>DMA: drain one completion
Pipeline->>Pipeline: refill freed staging buffer (encode next chunk)
Pipeline->>Pipeline: re-evaluate anyInFlight
end
end
alt no more data && anyInFlight
Pipeline->>Client: transition to COMPLETING / drain remaining
end
Estimated code review effort🎯 4 (Complex) | ⏱️ ~45 minutes Possibly related issues
Poem
🚥 Pre-merge checks | ✅ 4 | ❌ 1❌ Failed checks (1 warning)
✅ Passed checks (4 passed)
✏️ Tip: You can configure your own custom pre-merge checks in the settings. ✨ Finishing Touches📝 Generate docstrings
🧪 Generate unit tests (beta)
Warning There were issues while running some tools. Please review the errors and either fix the tool's configuration or disable the tool if it's a critical failure. 🔧 Infer (1.2.0)tests/platforms/esp/32/drivers/spi/spi_pingpong_pipeline_logic.cpptests/platforms/esp/32/drivers/spi/spi_pingpong_pipeline_logic.cpp:25:10: fatal error: 'fl/stl/cstddef.h' file not found ... [truncated 1178 characters] ... l-isystem" "/usr/local/include" "-internal-isystem" 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. Comment |
There was a problem hiding this comment.
Actionable comments posted: 2
🤖 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/spi/channel_driver_spi.cpp.hpp`:
- Around line 1503-1525: The code pre-consumes the second LED chunk by calling
encodeChunk into ch->stagingB and decrementing ch->ledBytesRemaining/advancing
ledSource before verifying spiStart succeeded, so if spiStart fails the chunk is
lost; modify the logic around encodeChunk/ch->stagingB and spiStart so you only
commit the consumption when spiStart returns ESP_OK (i.e. set ch->transBInFlight
= true and mPipeline.mEncodeIdx = 2 and actually decrement
ch->ledBytesRemaining/advance ledSource after successful spiStart), or if you
must encode early then on spiStart failure restore state by pushing the bytes in
ch->stagingB back into the ledSource, incrementing ch->ledBytesRemaining
accordingly and leaving mPipeline.mEncodeIdx unchanged; ensure
flags/transBInFlight are only set on success (functions/fields to touch:
encodeChunk, spiStart, ch->stagingB, ch->stagingCapacity, ch->ledBytesRemaining,
ledSource handling, ch->transBInFlight, mPipeline.mEncodeIdx).
In `@tests/platforms/esp/32/drivers/spi/spi_pingpong_pipeline_logic.cpp`:
- Around line 289-300: The test's boundary is off: 681 LEDs still fit in one
chunk so adjust the second case to use 683 LEDs (2049 LED bytes) so
PipelineModel::make(/*bytes=*/2049, ...) triggers two chunks; update the comment
math and change the assertion on big.queuedCount in the FL_TEST_CASE("Ping-pong
- 680-LED boundary regression (`#2304`)") to expect 2 after calling
big.startFirstDma(), referencing PipelineModel::make and startFirstDma to locate
the change.
🪄 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: d0c939fa-acc5-456b-a26b-1282dbcb8a4a
📒 Files selected for processing (2)
src/platforms/esp/32/drivers/spi/channel_driver_spi.cpp.hpptests/platforms/esp/32/drivers/spi/spi_pingpong_pipeline_logic.cpp
- channel_driver_spi.cpp.hpp: roll back ledSource/ledBytesRemaining if spiStart(transB) fails in the new startFirstDma() pre-queue path so the consumed chunk is re-encoded by the refill loop instead of being dropped (truncating the stream after A). - spi_pingpong_pipeline_logic.cpp: fix the boundary-regression test math. A 16 KB staging buffer fits exactly 2048 LED bytes (~682 RGB LEDs), so the previous "681 LED → 2 chunks" case (2043 < 2048) still fit in one chunk. Bump the small case to 2046 bytes and the big case to 2049 bytes so the assertion actually exercises the pre-queue path. Rename the test to "682-LED boundary regression" and update the comment. Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>
…ncodeIdx (refs #2304) The model's `stepStreaming` was choosing the refill buffer via `encodeIdx & 1`, which produces a strict A/B alternation independent of which buffer actually completed. With the FIFO drain rule ("A first if both in flight"), the parity-driven refill could write into a buffer that was still in flight — losing the original queue's identity and leaving one queue undrained at end-of-stream. Reproduction: the "all bytes accounted for after drain" test with TOTAL_BYTES = 12345 produced `queuedCount=25, completedCount=24` — exactly one chunk lost in the model. Fix: record which buffer the drain freed and target the refill there. That matches the real ESP-IDF SPI driver's per-buffer tracking — each staging buffer is queued independently and the refill goes to whichever slot just freed up. The encodeIdx counter is preserved as a queue counter but no longer drives buffer selection. CI failure on the original PR's CI run validates the fix path: > FAIL: Ping-pong - all bytes accounted for after drain > spi_pingpong_pipeline_logic.cpp:255: 25 == 24 After the fix: queued and completed counters match at end-of-stream. Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>
Summary
Closes the inter-chunk SPI gap that opens when a long WS2812B strip (>~680 LEDs) splits into multiple DMA transactions. The naive ping-pong (queue A → wait → queue B → wait → …) lets the SPI line idle for the host-task latency between chunks. Under RTOS contention that gap can exceed WS2812B's ~50 µs reset threshold and trigger a visible refresh on the strip.
Refs #2304. Hardware byte-equality + on-device timing validation deferred (call-out below).
What changed
`src/platforms/esp/32/drivers/spi/channel_driver_spi.cpp.hpp`:
dev_config.queue_size = 4was already in place); the ISR now transitions A → B without any host involvement, eliminating the inter-chunk gap. Cap is 2 in flight to keep the pipeline shallow and predictable.Tests added
`tests/platforms/esp/32/drivers/spi/spi_pingpong_pipeline_logic.cpp` (new, ~305 lines) — host-side state-machine tests with no ESP-IDF dependency. Models the buffer-rotation invariants in plain C++ and verifies:
Test plan
Both via `bash autoresearch --spi` on hardware. Next iteration.
Process note
The agent that drafted this PR was interrupted mid-stream when its `bash test --clean` (running from main checkout instead of the worktree) collided with stop-hook lock contention. The file deltas above are its pre-interruption work product, verified clean in the worktree at `feat/2304-spi-dma-pingpong`; main checkout was reverted of the leaked untracked test file. Recovered manually.
🤖 Generated with Claude Code
Summary by CodeRabbit
Bug Fixes
#2304).Tests
#2304regression.