Skip to content

refactor(esp32): hoist fractional clock-divider solver to core (#3562) - #3744

Merged
zackees merged 2 commits into
masterfrom
refactor/3562-shared-clock-divider
Jul 28, 2026
Merged

zackees merged 2 commits into
masterfrom
refactor/3562-shared-clock-divider

Conversation

@zackees

@zackees zackees commented Jul 27, 2026 •

Copy link
Copy Markdown
Member

Summary

Closes #3562.

solveI2sClockDivider() lived inside the I2S peripheral impl, but the 80 MHz APB / (N + B/A) math applies to every classic-ESP32 peripheral that takes a clkm_div_{num,a,b} triple — SPI, RMT4, I2S0.

Moved to platforms/esp/32/core/clock_divider.h as:

namespace fl { namespace platforms { namespace esp32 {
  struct ClkDividerNAB { int N; int A; int B; };
  ClkDividerNAB solveFractionalDivider(u32 base_hz, u32 target_hz,
                                       int max_A = 63, int min_N = 2) FL_NO_EXCEPT;
}}}

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=10 into shared math would silently hand every future consumer an I2S-specific default. The solver treats a zero target as degenerate and clamps to min_N rather than dividing by zero.

Verification — behaviour-preserving, checked two ways

1. Equivalence test. tests/platforms/esp/32/core/clock_divider.cpp keeps 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. esp32dev Blink is 391543 bytes before and after — byte-identical.

Why that size comparison is trustworthy

It nearly wasn't. compile_commands.json for esp32dev shows zero TUs matching i2s, 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 #error in 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 new clock_divider target
  • bash compile esp32dev --examples Blink — succeeds, flash unchanged at 391543 bytes
  • bash lint — green

Follow-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

  • New Features
    • Added/standardized fractional clock-divider solving for ESP32, including safe behavior for unspecified and extreme inputs.
  • Bug Fixes
    • Improved divider robustness with explicit clamping for zero inputs and ratio saturation to avoid undefined math.
    • Enhanced output accuracy via a fractional search approach and precision corner-case handling.
  • Refactor
    • Updated the ESP32 I2S clock-divider calculation to reuse the shared solver for consistent results.
  • Tests
    • Added host-side tests validating exact expected dividers, accuracy bounds, constraints, scaling, and saturation/degenerate cases.

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]>
@coderabbitai

coderabbitai Bot commented Jul 27, 2026 •

Copy link
Copy Markdown

Review Change Stack

No actionable comments were generated in the recent review. 🎉

ℹ️ Recent review info
⚙️ Run configuration

Configuration used: Path: .coderabbit.yaml

Review profile: CHILL

Plan: Pro Plus

Run ID: 10ff8484-4e89-4024-85f8-2e0a7cc0f553

📥 Commits

Reviewing files that changed from the base of the PR and between 4676122 and c171aec.

📒 Files selected for processing (3)
  • src/platforms/esp/32/core/clock_divider.h
  • src/platforms/esp/32/drivers/i2s/i2s_peripheral_esp32dev_esp.cpp.hpp
  • tests/platforms/esp/32/core/clock_divider.cpp
🚧 Files skipped from review as they are similar to previous changes (2)
  • tests/platforms/esp/32/core/clock_divider.cpp
  • src/platforms/esp/32/drivers/i2s/i2s_peripheral_esp32dev_esp.cpp.hpp

📝 Walkthrough

Walkthrough

Introduces 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.

Changes

ESP32 fractional clock-divider solver

Layer / File(s) Summary
Shared divider contract and solver
src/platforms/esp/32/core/clock_divider.h
Defines the APB clock constant, ClkDividerNAB, safety limit, and bounded fractional-divider search with invalid-input handling and precision corner-case adjustment.
I2S solver integration
src/platforms/esp/32/drivers/i2s/i2s_peripheral_esp32dev_esp.cpp.hpp
Replaces the local double-based divider calculation with the shared solver and retains the 8 MHz default for unspecified targets.
Host-side solver validation
tests/platforms/esp/32/core/clock_divider.cpp
Tests reference-output compatibility, exact 8 MHz division, hardware bounds, frequency accuracy, base-clock scaling, minimum-divider clamping, saturation, and zero-input handling.

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
Loading
🚥 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 is concise and accurately describes the main change: hoisting the ESP32 fractional clock-divider solver into shared core code.
Linked Issues check ✅ Passed The PR covers the shared helper, I2S integration, and regression coverage; deferred SPI/RMT4 work is consistent with the issue's staged scope.
Out of Scope Changes check ✅ Passed The divider limit, field rename, and tests are directly tied to the refactor and do not appear unrelated to the stated objectives.
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 refactor/3562-shared-clock-divider

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.

@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: 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

📥 Commits

Reviewing files that changed from the base of the PR and between a87f15c and 4676122.

📒 Files selected for processing (3)
  • src/platforms/esp/32/core/clock_divider.h
  • src/platforms/esp/32/drivers/i2s/i2s_peripheral_esp32dev_esp.cpp.hpp
  • tests/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]>
@zackees
zackees merged commit 75b1f71 into master Jul 28, 2026
28 checks passed
@zackees
zackees deleted the refactor/3562-shared-clock-divider branch July 28, 2026 04:11
@fastled-project-sync fastled-project-sync Bot moved this from Triage to Done in FastLED Tracker Jul 28, 2026
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.

Hoist solveI2sClockDivider() to shared location; apply to other drivers

1 participant