Skip to content

Conversation

@DedeHai
Copy link

@DedeHai DedeHai commented Jul 11, 2025

please thouroughly check the #ifdefs, there are just too many variants... I tested with modfied env on S2 only.
The driver itself is tested and working on C3, S2 and S3 (with AC code, see wled#4761)

The platformio.ini is a bit messy and inconsistent for S2 and C3, IMHO its in desperate need of a cleanup for these.

Summary by CodeRabbit

  • New Features

    • Added support for analog microphone input using DMA ADC sampling on ESP32-S2, ESP32-C3, and ESP32-S3 devices (ESP-IDF 4.4.0+).
    • Expanded configuration options and UI elements for analog microphone input on supported ESP32 variants.
  • Improvements

    • Enhanced detection and handling of analog microphone sources across more ESP32 models.
    • Improved configuration and information display for analog microphone input settings.

@coderabbitai
Copy link

coderabbitai bot commented Jul 11, 2025

Walkthrough

The changes expand analog microphone support for ESP32 microcontrollers, adding DMA ADC sampling for ESP32-S2, ESP32-C3, and ESP32-S3 targets using ESP-IDF 4.4.0 or later. Conditional compilation and type checks are updated, a new DMAadcSource class is introduced, and configuration/UI logic is generalized for these new targets.

Changes

File(s) Change Summary
usermods/audioreactive/audio_reactive.h Updated conditional compilation for analog mic support; logic and UI generalized for new ESP32 targets; type checks and JSON config updated.
usermods/audioreactive/audio_source.h Renamed enum type; added DMAadcSource class for DMA ADC sampling; updated conditional logic for analog input support.

Sequence Diagram(s)

sequenceDiagram
    participant User
    participant AudioReactive
    participant I2SAdcSource
    participant DMAadcSource

    User->>AudioReactive: Configure analog microphone input
    AudioReactive->>AudioReactive: Check target (classic ESP32 or S2/C3/S3)
    alt Classic ESP32
        AudioReactive->>I2SAdcSource: initialize(audioPin)
        I2SAdcSource-->>AudioReactive: Ready for sampling
    else DMA ADC Supported Target
        AudioReactive->>DMAadcSource: initialize(audioPin)
        DMAadcSource-->>AudioReactive: Ready for sampling
    end
    AudioReactive->>AudioReactive: Start FFT processing with selected source
Loading

Poem

In circuits and code, a leap we take,
DMA ADC now wide awake!
S2, C3, S3 join the song,
Analog mics can now belong.
With pins and buffers, samples flow—
Bunnies cheer, “Let the music grow!”
🐇🎶


📜 Recent review details

Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between e4fa40b and 66a50cd.

📒 Files selected for processing (2)
  • usermods/audioreactive/audio_reactive.h (11 hunks)
  • usermods/audioreactive/audio_source.h (4 hunks)
🚧 Files skipped from review as they are similar to previous changes (1)
  • usermods/audioreactive/audio_reactive.h
🧰 Additional context used
🧠 Learnings (2)
📓 Common learnings
Learnt from: DedeHai
PR: MoonModules/WLED-MM#253
File: usermods/audioreactive/audio_source.h:1256-1261
Timestamp: 2025-07-12T04:20:14.523Z
Learning: In WLED AudioReactive usermod, DC offset removal optimization in DMAadcSource::getSamples() should be implemented after PR #248 merges, which will change the sample buffer from float to int16. This eliminates the need for temporary integer buffers and allows direct integer arithmetic on the native buffer type for better memory efficiency on resource-constrained MCUs like C3 and S2.
Learnt from: DedeHai
PR: MoonModules/WLED-MM#248
File: usermods/audioreactive/audio_reactive.h:199-200
Timestamp: 2025-06-30T17:53:37.232Z
Learning: In WLED AudioReactive usermod, when using ArduinoFFT (enabled via UM_AUDIOREACTIVE_USE_ARDUINO_FFT), it's acceptable and necessary to redefine the global sqrt macro to sqrtf within the conditional compilation block for performance optimization. This is a specific requirement for ArduinoFFT optimization that can provide 10-50% performance improvement on ESP32.
usermods/audioreactive/audio_source.h (3)
Learnt from: DedeHai
PR: MoonModules/WLED-MM#253
File: usermods/audioreactive/audio_source.h:1256-1261
Timestamp: 2025-07-12T04:20:14.523Z
Learning: In WLED AudioReactive usermod, DC offset removal optimization in DMAadcSource::getSamples() should be implemented after PR #248 merges, which will change the sample buffer from float to int16. This eliminates the need for temporary integer buffers and allows direct integer arithmetic on the native buffer type for better memory efficiency on resource-constrained MCUs like C3 and S2.
Learnt from: DedeHai
PR: MoonModules/WLED-MM#248
File: usermods/audioreactive/audio_reactive.h:199-200
Timestamp: 2025-06-30T17:53:37.232Z
Learning: In WLED AudioReactive usermod, when using ArduinoFFT (enabled via UM_AUDIOREACTIVE_USE_ARDUINO_FFT), it's acceptable and necessary to redefine the global sqrt macro to sqrtf within the conditional compilation block for performance optimization. This is a specific requirement for ArduinoFFT optimization that can provide 10-50% performance improvement on ESP32.
Learnt from: DedeHai
PR: MoonModules/WLED-MM#248
File: usermods/audioreactive/audio_reactive.h:1121-1121
Timestamp: 2025-06-30T17:58:27.987Z
Learning: In WLED AudioReactive usermod's runMicFilter function, the different cutoff frequencies between float (80Hz) and integer (90Hz) FFT implementations are intentional. The higher 90Hz cutoff for integer math helps preserve precision by avoiding overly aggressive filtering where integer arithmetic limitations could compound errors. The 10Hz difference between 80Hz and 90Hz is negligible from an audio performance standpoint but provides better precision for integer calculations.
⏰ Context from checks skipped due to timeout of 90000ms. You can increase the timeout in your CodeRabbit configuration to a maximum of 15 minutes (900000ms). (20)
  • GitHub Check: Builds (athom_music_esp32_4MB_M)
  • GitHub Check: Builds (adafruit_matrixportal_esp32s3_tinyUF2)
  • GitHub Check: Builds (seeed_esp32c3_4MB_S)
  • GitHub Check: Builds (esp8266pro_16MB_M)
  • GitHub Check: Builds (esp32S3_WROOM-2_M)
  • GitHub Check: Builds (esp8266_4MB_S)
  • GitHub Check: Builds (esp01_1MB_S)
  • GitHub Check: Builds (esp32c3dev_4MB_M)
  • GitHub Check: Builds (esp32c3dev_2MB_M)
  • GitHub Check: Builds (esp32c3mini_dio_4MB_M)
  • GitHub Check: Builds (esp32s2_PSRAM_M)
  • GitHub Check: Builds (esp32S3_4MB_S)
  • GitHub Check: Builds (esp32S3_8MB_PSRAM_M)
  • GitHub Check: Builds (esp32S3_4MB_PSRAM_M)
  • GitHub Check: Builds (esp32_16MB_V4_M)
  • GitHub Check: Builds (esp32_4MB_V4_S)
  • GitHub Check: Builds (esp32S3_8MB_S)
  • GitHub Check: Builds (esp32S3_8MB_M)
  • GitHub Check: Builds (esp32_16MB_V4_S)
  • GitHub Check: Builds (esp32_4MB_V4_HUB75_forum)
🔇 Additional comments (3)
usermods/audioreactive/audio_source.h (3)

167-167: LGTM: Improved enum naming for broader ADC support.

The rename from Type_I2SAdc to Type_ADC makes the enum value more generic and appropriate for both I2S ADC and DMA ADC sampling methods.


986-986: LGTM: Consistent with enum rename.

The updated return value correctly uses the new Type_ADC enum name.


1145-1308: Well-implemented DMA ADC source with comprehensive functionality.

The DMAadcSource class provides a robust implementation for ADC sampling using DMA on supported ESP32 variants. The implementation includes proper initialization, error handling, buffer management, and cleanup. The conditional compilation ensures it's only available on compatible targets.

Key strengths:

  • Proper ADC DMA configuration with appropriate buffer sizing
  • Comprehensive error handling including buffer overrun recovery
  • Clean resource management with pin allocation/deallocation
  • Efficient sample reading with partial frame handling

The TODO comment about DC offset optimization correctly identifies that integer arithmetic would be more efficient and aligns with the plan to implement this after PR #248 merges when the buffer changes from float to int16.

✨ Finishing Touches
  • 📝 Generate Docstrings

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
🪧 Tips

Chat

There are 3 ways to chat with CodeRabbit:

  • Review comments: Directly reply to a review comment made by CodeRabbit. Example:
    • I pushed a fix in commit <commit_id>, please review it.
    • Explain this complex logic.
    • Open a follow-up GitHub issue for this discussion.
  • Files and specific lines of code (under the "Files changed" tab): Tag @coderabbitai in a new review comment at the desired location with your query. Examples:
    • @coderabbitai explain this code block.
    • @coderabbitai modularize this function.
  • PR comments: Tag @coderabbitai in a new PR comment to ask questions about the PR branch. For the best results, please provide a very specific query, as very limited context is provided in this mode. Examples:
    • @coderabbitai gather interesting stats about this repository and render them as a table. Additionally, render a pie chart showing the language distribution in the codebase.
    • @coderabbitai read src/utils.ts and explain its main purpose.
    • @coderabbitai read the files in the src/scheduler package and generate a class diagram using mermaid and a README in the markdown format.
    • @coderabbitai help me debug CodeRabbit configuration file.

Support

Need help? Create a ticket on our support page for assistance with any issues or questions.

Note: Be mindful of the bot's finite context window. It's strongly recommended to break down tasks such as reading entire modules into smaller chunks. For a focused discussion, use review comments to chat about specific files and their changes, instead of using the PR comments.

CodeRabbit Commands (Invoked using PR comments)

  • @coderabbitai pause to pause the reviews on a PR.
  • @coderabbitai resume to resume the paused reviews.
  • @coderabbitai review to trigger an incremental review. This is useful when automatic reviews are disabled for the repository.
  • @coderabbitai full review to do a full review from scratch and review all the files again.
  • @coderabbitai summary to regenerate the summary of the PR.
  • @coderabbitai generate docstrings to generate docstrings for this PR.
  • @coderabbitai generate sequence diagram to generate a sequence diagram of the changes in this PR.
  • @coderabbitai resolve resolve all the CodeRabbit review comments.
  • @coderabbitai configuration to show the current CodeRabbit configuration for the repository.
  • @coderabbitai help to get help.

Other keywords and placeholders

  • Add @coderabbitai ignore anywhere in the PR description to prevent this PR from being reviewed.
  • Add @coderabbitai summary to generate the high-level summary at a specific location in the PR description.
  • Add @coderabbitai anywhere in the PR title to generate the title automatically.

CodeRabbit Configuration File (.coderabbit.yaml)

  • You can programmatically configure CodeRabbit by adding a .coderabbit.yaml file to the root of your repository.
  • Please see the configuration documentation for more information.
  • If your editor has YAML language server enabled, you can add the path at the top of this file to enable auto-completion and validation: # yaml-language-server: $schema=https://coderabbit.ai/integrations/schema.v2.json

Documentation and Community

  • Visit our Documentation for detailed information on how to use CodeRabbit.
  • Join our Discord Community to get help, request features, and share feedback.
  • Follow us on X/Twitter for updates and announcements.

Copy link

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

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

Actionable comments posted: 5

🧹 Nitpick comments (5)
usermods/audioreactive/audio_reactive.h (4)

69-73: Consider simplifying the target check with a helper macro.

The condition for enabling DMA ADC sampling could be more readable with a helper macro to avoid repeating the target checks throughout the codebase.

+// Helper macro for ESP32 variants that support DMA ADC
+#define ESP32_VARIANT_WITH_DMA_ADC (defined(CONFIG_IDF_TARGET_ESP32S2) || defined(CONFIG_IDF_TARGET_ESP32C3) || defined(CONFIG_IDF_TARGET_ESP32S3))
+
 // Analog mic with DMA ADC sampling is only supported on ESP32-S2, ESP32-C3 and ESP32-S3 on IDF >= 4.4.0
-#if !defined(CONFIG_IDF_TARGET_ESP32) && (ESP_IDF_VERSION >= ESP_IDF_VERSION_VAL(4, 4, 0) && (defined(CONFIG_IDF_TARGET_ESP32S2) || defined(CONFIG_IDF_TARGET_ESP32C3) || defined(CONFIG_IDF_TARGET_ESP32S3)))
+#if !defined(CONFIG_IDF_TARGET_ESP32) && (ESP_IDF_VERSION >= ESP_IDF_VERSION_VAL(4, 4, 0)) && ESP32_VARIANT_WITH_DMA_ADC
 #define AR_DMA_ADC_SAMPLING
 #endif

918-918: Update the comment to reflect the new type check.

The comment above this line still references Type_I2SAdc, but the code now checks for the more generic Type_ADC.

Update the comment on line 918 to mention Type_ADC instead of Type_I2SAdc to maintain consistency with the code change.


1244-1246: Reduce #ifdef complexity with a unified macro for analog support.

The pattern defined(CONFIG_IDF_TARGET_ESP32) || defined(AR_DMA_ADC_SAMPLING) is repeated throughout the file. Consider defining a helper macro to improve readability and maintainability.

Add this near the top of the file after defining AR_DMA_ADC_SAMPLING:

+// Helper macro to check if analog microphone is supported
+#define SUPPORTS_ANALOG_MIC (defined(CONFIG_IDF_TARGET_ESP32) || defined(AR_DMA_ADC_SAMPLING))

Then replace all occurrences:

-#if defined(CONFIG_IDF_TARGET_ESP32) || defined(AR_DMA_ADC_SAMPLING)
+#if SUPPORTS_ANALOG_MIC

Also applies to: 2813-2816


69-73: Consider a more modular approach to handle platform-specific code.

The numerous #ifdef conditionals make the code difficult to follow, as you noted. Consider refactoring platform-specific code into separate initialization functions or even separate files:

  1. Create platform-specific initialization functions (e.g., initAnalogMicESP32(), initAnalogMicDMA())
  2. Use a single conditional block to select the appropriate function
  3. This would reduce nesting and make the code flow clearer

Additionally, consider documenting the supported configurations in a table format in the code comments to help developers understand which features are available on which platforms.

Also applies to: 1972-2110

usermods/audioreactive/audio_source.h (1)

1177-1177: Consider making ADC attenuation configurable.

The ADC attenuation is hardcoded to ADC_ATTEN_DB_11 (≈0-2.5V range). Different microphones or audio sources might require different voltage ranges for optimal signal quality.

Consider adding an attenuation parameter to the constructor or making it configurable:

+    DMAadcSource(SRate_t sampleRate, int blockSize, float sampleScale = 1.0f, adc_atten_t attenuation = ADC_ATTEN_DB_11) :
       AudioSource(sampleRate, blockSize, sampleScale, false) {
         // ...
         adcpattern = {
-          .atten = ADC_ATTEN_DB_11,               // approx. 0-2.5V input range
+          .atten = attenuation,                   // configurable input range
           .channel = 0,
           // ...
📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between daa8103 and e4fa40b.

📒 Files selected for processing (2)
  • usermods/audioreactive/audio_reactive.h (11 hunks)
  • usermods/audioreactive/audio_source.h (4 hunks)
🧰 Additional context used
🧠 Learnings (3)
📓 Common learnings
Learnt from: DedeHai
PR: MoonModules/WLED-MM#248
File: usermods/audioreactive/audio_reactive.h:199-200
Timestamp: 2025-06-30T17:53:37.232Z
Learning: In WLED AudioReactive usermod, when using ArduinoFFT (enabled via UM_AUDIOREACTIVE_USE_ARDUINO_FFT), it's acceptable and necessary to redefine the global sqrt macro to sqrtf within the conditional compilation block for performance optimization. This is a specific requirement for ArduinoFFT optimization that can provide 10-50% performance improvement on ESP32.
usermods/audioreactive/audio_reactive.h (3)

undefined

<retrieved_learning>
Learnt from: DedeHai
PR: #248
File: usermods/audioreactive/audio_reactive.h:199-200
Timestamp: 2025-06-30T17:53:37.232Z
Learning: In WLED AudioReactive usermod, when using ArduinoFFT (enabled via UM_AUDIOREACTIVE_USE_ARDUINO_FFT), it's acceptable and necessary to redefine the global sqrt macro to sqrtf within the conditional compilation block for performance optimization. This is a specific requirement for ArduinoFFT optimization that can provide 10-50% performance improvement on ESP32.
</retrieved_learning>

<retrieved_learning>
Learnt from: DedeHai
PR: #248
File: usermods/audioreactive/audio_reactive.h:1121-1121
Timestamp: 2025-06-30T17:58:27.987Z
Learning: In WLED AudioReactive usermod's runMicFilter function, the different cutoff frequencies between float (80Hz) and integer (90Hz) FFT implementations are intentional. The higher 90Hz cutoff for integer math helps preserve precision by avoiding overly aggressive filtering where integer arithmetic limitations could compound errors. The 10Hz difference between 80Hz and 90Hz is negligible from an audio performance standpoint but provides better precision for integer calculations.
</retrieved_learning>

<retrieved_learning>
Learnt from: netmindz
PR: #248
File: platformio.ini:1613-1613
Timestamp: 2025-07-02T23:22:57.175Z
Learning: In WLED platformio.ini, the particle system disable flags (WLED_DISABLE_PARTICLESYSTEM1D and WLED_DISABLE_PARTICLESYSTEM2D) are intentionally varied across different build environments based on platform memory constraints. More memory-limited platforms (like ESP8266, ESP32-C3, ESP32-S2) disable both 1D and 2D particle systems, while platforms with more available memory (like esp32_4MB_V4_S with 4MB flash) may only disable the 1D version to preserve flash space while keeping 2D functionality available.
</retrieved_learning>

usermods/audioreactive/audio_source.h (1)
Learnt from: DedeHai
PR: MoonModules/WLED-MM#248
File: usermods/audioreactive/audio_reactive.h:199-200
Timestamp: 2025-06-30T17:53:37.232Z
Learning: In WLED AudioReactive usermod, when using ArduinoFFT (enabled via UM_AUDIOREACTIVE_USE_ARDUINO_FFT), it's acceptable and necessary to redefine the global sqrt macro to sqrtf within the conditional compilation block for performance optimization. This is a specific requirement for ArduinoFFT optimization that can provide 10-50% performance improvement on ESP32.
⏰ Context from checks skipped due to timeout of 90000ms. You can increase the timeout in your CodeRabbit configuration to a maximum of 15 minutes (900000ms). (20)
  • GitHub Check: Builds (esp32c3dev_4MB_M)
  • GitHub Check: Builds (esp8266_2MB_S)
  • GitHub Check: Builds (seeed_esp32c3_4MB_S)
  • GitHub Check: Builds (esp8266_4MB_S)
  • GitHub Check: Builds (esp32c3mini_dio_4MB_M)
  • GitHub Check: Builds (esp32S3_16MB_PSRAM_M_HUB75)
  • GitHub Check: Builds (esp32S3_WROOM-2_M)
  • GitHub Check: Builds (esp32s2_PSRAM_S)
  • GitHub Check: Builds (esp32S3_8MB_PSRAM_M)
  • GitHub Check: Builds (esp32s2_PSRAM_M)
  • GitHub Check: Builds (esp32S3_4MB_PSRAM_M)
  • GitHub Check: Builds (esp32S3_4MB_PSRAM_S)
  • GitHub Check: Builds (esp32S3_8MB_M)
  • GitHub Check: Builds (esp32S3_4MB_S)
  • GitHub Check: Builds (esp32S3_8MB_S)
  • GitHub Check: Builds (esp32_16MB_V4_M)
  • GitHub Check: Builds (esp32_16MB_V4_S)
  • GitHub Check: Builds (esp32_4MB_V4_S)
  • GitHub Check: Builds (esp32_4MB_PSRAM_S)
  • GitHub Check: Builds (esp32_4MB_V4_HUB75_forum)
🔇 Additional comments (5)
usermods/audioreactive/audio_reactive.h (2)

2099-2107: Verify the intentional difference in buffer sizes between ADC sources.

The code uses different buffer sizes for different ADC sources:

  • I2SAdcSource uses BLOCK_SIZE (line 2101)
  • DMAadcSource uses samplesFFT (line 2106)

Is this difference intentional? If so, consider adding a comment explaining why different buffer sizes are needed.


2105-2107: DMAadcSource implementation confirmed and Type_ADC mapping is correct.

  • usermods/audioreactive/audio_source.h defines class DMAadcSource inheriting from AudioSource.
  • The AudioSourceType enum includes Type_ADC.
  • Both I2SAdcSource::getType() and DMAadcSource::getType() return Type_ADC.
  • No lingering Type_I2SAdc references remain.

No changes needed.

usermods/audioreactive/audio_source.h (3)

167-167: LGTM!

The rename from Type_I2SAdc to Type_ADC is appropriate as it's more generic and covers both I2S ADC and DMA ADC implementations.


986-986: LGTM!

The type update is consistent with the enum rename.


1238-1254: DMA buffer flush via reset_DMA_ADC is in place and functioning

The reset_DMA_ADC() routine (usermods/audioreactive/audio_source.h lines 1303–1308) stops, deinitializes, reinitializes and restarts the ADC DMA—effectively flushing the buffer after an overflow. No change is strictly required to “flush the DMA buffer completely.”

• reset_DMA_ADC implementation:
• stops DMA (adc_digi_stop())
• deinitializes (adc_digi_deinitialize())
• reinitializes (init_adc_continuous())
• restarts sampling (adc_digi_start())

Optional enhancements (if you see remaining glitches):

  • Add a simple frame-sync marker or phase counter in the sample stream to detect mis-alignment
  • Instrument a counter or debug log for each ESP_ERR_INVALID_STATE occurrence to monitor frequency of buffer overruns

@DedeHai
Copy link
Author

DedeHai commented Jul 12, 2025

not sure why the seeed env on C3 fails, it is not failing locally. maybe IDF version check for ADC support needs to be increased to 4.4.4.

@drlovedotcom
Copy link

Hi,
The recently added "Gif" button somehow vanished with this commit...

@DedeHai
Copy link
Author

DedeHai commented Jul 14, 2025

@drlovedotcom you are mistaken.

@spiro-c
Copy link

spiro-c commented Jul 14, 2025

the gif button is not merged yet #240

@netmindz netmindz requested a review from softhack007 July 16, 2025 11:43
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants