Repository navigation
refactor(esp32): hoist fractional clock-divider solver to core (#3562) - #3744
Conversation
solveI2sClockDivider() lived inside the I2S peripheral impl, but the
80 MHz-APB / (N + B/A) math is shared by every classic-ESP32 peripheral that
takes a clkm_div_{num,a,b} triple -- SPI, RMT4, I2S0. Moves it to
platforms/esp/32/core/clock_divider.h as
fl::platforms::esp32::solveFractionalDivider(), generalised over the base
clock and the hardware limits (max_A, min_N).
The I2S call site keeps its own 8 MHz fallback rather than pushing it into
the shared solver: "what frequency do we want when none is configured" is a
driver policy, not divider arithmetic. The solver treats a zero target as
degenerate and clamps to min_N instead of dividing by zero.
Behaviour-preserving, verified two ways:
- tests/platforms/esp/32/core/clock_divider.cpp carries a verbatim copy of
the pre-hoist function and asserts the new solver returns identical
(N, A, B) across the frequency band the I2S driver uses. A refactor that
quietly retuned the divider would not fail any build, so the equivalence
has to be pinned by a test.
- esp32dev Blink is 391543 bytes before and after -- byte-identical.
The size comparison only means something because the header is actually in
that build: confirmed by a negative control (a temporary #error in the
header failed the build from 8 unity TUs). The file path never appears in
compile_commands.json because the drivers are unity-built, so "no i2s TU"
there is not evidence of exclusion.
Co-Authored-By: Claude <[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 Plus Run ID: 📒 Files selected for processing (3)
🚧 Files skipped from review as they are similar to previous changes (2)
📝 WalkthroughWalkthroughIntroduces a shared host-testable ESP32 fractional clock-divider solver, updates the I2S peripheral to use it, and adds tests covering compatibility, bounds, accuracy, scaling, clamping, saturation, and degenerate inputs. ChangesESP32 fractional clock-divider solver
Estimated code review effort: 3 (Moderate) | ~20 minutes Sequence Diagram(s)sequenceDiagram
participant I2SDriver
participant SharedSolver
participant HostTests
I2SDriver->>SharedSolver: solve 80 MHz divider
SharedSolver-->>I2SDriver: return n, a, b
HostTests->>SharedSolver: solve test frequencies and edge cases
SharedSolver-->>HostTests: return divider results
HostTests->>HostTests: compare reference, bounds, and realised frequency
🚥 Pre-merge checks | ✅ 5✅ Passed checks (5 passed)
✨ Finishing Touches📝 Generate docstrings
🧪 Generate unit tests (beta)
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: 3
🤖 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/core/clock_divider.h`:
- Around line 56-103: Move the solveFractionalDivider function body out of
clock_divider.h into the appropriate .impl.hpp or .cpp.hpp implementation file,
leaving only its declaration in the header. Preserve the existing signature,
defaults, FL_NO_EXCEPT annotation, and behavior while ensuring the header
contains no newly introduced non-template function definition.
- Around line 31-35: Rename the ClkDividerNAB members N, A, and B to lowercase
n, a, and b, then update all I2S and test consumers to use the new member names
while preserving behavior.
- Around line 56-71: Update solveFractionalDivider to validate the computed
base_hz/target_hz divider against the representable range of ClkDividerNAB::N
before converting it to int, returning the established error result for values
above the supported maximum. Preserve the existing minimum-divider handling for
valid values, and add clock-divider tests covering overflow and oversized
divider inputs.
🪄 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 Plus
Run ID: c8d79f61-5a61-4476-9572-9b252b56fc02
📒 Files selected for processing (3)
src/platforms/esp/32/core/clock_divider.hsrc/platforms/esp/32/drivers/i2s/i2s_peripheral_esp32dev_esp.cpp.hpptests/platforms/esp/32/core/clock_divider.cpp
Review follow-up on #3744. 1. Overflow (real): base_hz / target_hz can exceed INT_MAX for extreme u32 pairs -- 4294967295 / 1 is ~4.29e9 against an INT_MAX of ~2.147e9 -- so static_cast<int> on the ratio was undefined. Saturate to kMaxDivider BEFORE the cast; clamping afterwards is not possible because there is no defined value left to clamp. Not reachable from the I2S caller (it passes >= 8 MHz), but this is now a shared helper other drivers will call with their own inputs, so it should not have an undefined corner. kMaxDivider is deliberately an int-representability bound, not a hardware one -- the real fields are far narrower (I2S clkm_div_num is 8 bits). Adding a hardware cap here would change results for existing low-frequency inputs, which does not belong in a byte-identical refactor. 2. Naming: ClkDividerNAB members N/A/B -> n/a/b, matching the plain-aggregate convention (cpp-standards.md exemplar `struct CacheKey { ... u32 version; int cct; }`). The uppercase spelling stays in the doc comments, where it maps to the datasheet's clkm_conf.clkm_div_{num,a,b}. Validation: 274/274 tests pass including a new oversized-ratio case; bash lint green; esp32dev Blink still 391543 bytes, so the refactor remains byte-identical. Co-Authored-By: Claude <[email protected]>
Summary
Closes #3562.
solveI2sClockDivider()lived inside the I2S peripheral impl, but the80 MHz APB / (N + B/A)math applies to every classic-ESP32 peripheral that takes aclkm_div_{num,a,b}triple — SPI, RMT4, I2S0.Moved to
platforms/esp/32/core/clock_divider.has:Pure arithmetic, no ESP headers — so it compiles and unit-tests on the host.
One deliberate design choice
The I2S call site keeps its own 8 MHz fallback instead of pushing it into the shared solver. "What frequency do we want when none is configured" is driver policy, not divider arithmetic — baking
N=10into shared math would silently hand every future consumer an I2S-specific default. The solver treats a zero target as degenerate and clamps tomin_Nrather than dividing by zero.Verification — behaviour-preserving, checked two ways
1. Equivalence test.
tests/platforms/esp/32/core/clock_divider.cppkeeps a verbatim copy of the pre-hoist function and asserts the new solver returns identical(N, A, B)across the band the I2S driver actually uses (100 kHz → 40 MHz). This matters because a refactor that quietly retuned the divider would not fail any build — it would just shift every driver's output clock. Plus coverage for hardware limits (A ≤ 63,B < A,N ≥ min_N), realised-frequency error, base-clock generalisation, and degenerate inputs.2. Binary comparison.
esp32devBlink is 391543 bytes before and after — byte-identical.Why that size comparison is trustworthy
It nearly wasn't.
compile_commands.jsonforesp32devshows zero TUs matchingi2s, which looks like the changed code isn't in the build at all — making a byte-identical size meaningless.It isn't excluded; the drivers are unity-built, so the individual file path never appears. I confirmed the header really is compiled with a negative control: a temporary
#errorin it failed the build, reported from 8 unity TUs. Then reverted and re-verified green.Flagging that because "grep compile_commands.json for the filename" is the obvious way to check this and it gives the wrong answer here.
Testing
bash test --cpp— all pass, including the newclock_dividertargetbash compile esp32dev --examples Blink— succeeds, flash unchanged at 391543 bytesbash lint— greenFollow-on
This only hoists the math and repoints I2S at it. Actually adopting it in SPI / RMT4 (the rest of #3562's "apply to other drivers") is left alone — each needs its own register marshalling and bench validation, and bundling that here would make an intentionally byte-identical refactor into a behavioural change.
🤖 Generated with Claude Code
Summary by CodeRabbit