Skip to content

Prepare Audio Subsystem for IDF5/Arduino 3.0, Harden S3 Support, add simulated beat. - #801

Merged
rbergen merged 6 commits into
PlummersSoftwareLLC:mainfrom
robertlipe:refactor/modern-i2s
Apr 10, 2026
Merged

rbergen merged 6 commits into
PlummersSoftwareLLC:mainfrom
robertlipe:refactor/modern-i2s

Conversation

@robertlipe

Copy link
Copy Markdown
Collaborator

Prepare Audio Subsystem for IDF5/Arduino 3.0, Harden S3 Support

It's my goal to land this before we switch, but to have the code in the
tree. It needs to be exercided on more hardware than I have right now
(it's fine on the analog mic of Mesmerizer) but it deserves widespread
testing.

I'm going to mar this as "pending" WIP, but go ahead and get it on
the group's repo so that those of us that care about such things will
have a centralized place for going so.

Gemini help me wrangle this code to "prove" it's right, so
I'll let it bigger rest of this.)

Summary

Refactoring the audio subsystem to break free from legacy technical debt,
preparing for the inevitable migration to ESP-IDF 5 and Arduino 3.0.

It tackles the brittleness of our audio input handling by properly
adhering to the "Five Modes" of input (M5Stack, Modern I2S, Legacy I2S,
Modern ADC, Legacy ADC) and ensuring that newer hardware (ESP32-S3)
doesn't panic when faced with older configuration patterns.

Key Changes:

  • iModernization & Future-Proofing:

    • IDF 5 Readiness*: explicitly guards legacy ADC logic (which
      disappears in IDF 5) and prepares the "Modern" paths to be
      the primary citizens. Old paths will be deleted later.`

    • Refactored Initialization*:
      Cleans up the InitAudioInput logic to respect hardware
      capability (SOC_I2S_SUPPORTS_ADC) rather than just checking board
      defines, preventing invalid driver installs on S3. (Like the ones I use...)

  • Hardware Stability (The "Five Modes"):

    • Formalizes the initialization order for our mixed fleet of hardware.
    • Crash Prevention*: Adds strict guards (INPUT_PIN < 0) to
      SampleAudio (_We should probably make THAT default in globals.h>
      to prevent LoadProhibited panics on devices that skip hardware
      init. This allows a device to exist in a "Simulated Audio Only"
      state without crashing the kernel.
  • Feature: Runtime SimBeat:

    • Exposes simbeat [on|off] [bpm] in the CLI. Decouples "Audio
      Effects" from "Physical Audio Hardware," empowering developers
      to test reactive effects on the couch without a microphone or an audio source.

Context:

We are clearing the path to adopt standard ESP-IDF 5 practices while
maintaining support for our legacy fleet. This PR ensures that i2s_config_t
and adc_pattern usage remains safe as struct definitions evolve in newer
SDKs, moving us away from "hope-based compilation" to robust, capability-checked
configuration.

Description

Contributing requirements

  • I read the contribution guidelines in CONTRIBUTING.md.
  • I understand the BlinkenPerBit metric, and maximized it in this PR.
  • I selected main as the target branch.
  • All code herein is subjected to the license terms in COPYING.txt.

It's my goal to land this before we switch, but to have the code in the
tree. It needs to be exercided on more hardware than I have right now
(it's fine on the analog mic of Mesmerizer) but it deserves widespread
testing.  (Gemini help me wrangle this code to "prove" it's right, so
I'll let it bigger part rest of this.)
@robertlipe robertlipe changed the title `0kasdf Prepare Audio Subsystem for IDF5/Arduino 3.0, Harden S3 Support, add simulated beat. Dec 22, 2025
@rbergen

rbergen commented Dec 22, 2025

Copy link
Copy Markdown
Collaborator

My PR housekeeping question about this one is why you opened it as a draft? You know my opinion on these. ;)

@robertlipe

robertlipe commented Dec 22, 2025 •

Copy link
Copy Markdown
Collaborator Author

I know. I also don't like that I can't really test all five paths because just don't have the hardware with me and I know you don't like things we haven't SEEN run.

Could we just submit it and fix on fail? Certainly wouldn't be the first on the audio path. (You know I'm not a fly by night on such things, either.)

Basically I needed this in two different branches of mine.. if you want me to keep this in my fork for longer, that's ok.

You can kick it into the field or out of the stadium. I'm flexible. I'm just recording my work somewhat publicly.

@rbergen

rbergen commented Dec 27, 2025

Copy link
Copy Markdown
Collaborator

I know this is a topic we have different perspectives on. However, particularly with something as brittle as audio has proven to be, I really don't want to take the "run with it and hope for the best" approach, this broadly. It may be weeks or months before a problem we'd introduce today pops up, at which time it's not unlikely we have completely forgotten this particular PR as the/a possible culprit.

So, I suggest we wait with merging this one until we do have the opportunity to test this more comprehensively than is now possible. I say "more comprehensively" because I don't mean we have to test every permutation, but a decent representation at least.

If I can contribute to that, then let me know how.

@robertlipe

Copy link
Copy Markdown
Collaborator Author

That's why it's marked as draft.

I want to get it some airtime for those able/willing to exercise it (which includes me, between branches of development).

It's not a merge candidate right now.

If this causes you stress (the opposite of my goal) then I'll pull this and quarantine it back into my trees where only I can/will see it. It's just another local change for me to carry around...

This commit reconciles divergent audio backends into a unified template-based
system support modern ESP-IDF 5 while maintaining legacy compatibility.

Key improvements:
- Modernized spectral processing loops using std::transform for SIMD/S3-era efficiency.
- Stabilized SimulateBeatPass by fixing uninitialized memory ghosting and matching
  psychoacoustic traits (cube-root compression).
- Enforced project-wide include hygiene: globals.h priority and dictionary-sorting.
- Resolved hardware deprecation warnings in the LilyGo amoled driver.
- Sanitized worktree: Full trailing whitespace removal.
@robertlipe
robertlipe force-pushed the refactor/modern-i2s branch from d8f845d to e71b41c Compare April 8, 2026 09:08
@robertlipe

Copy link
Copy Markdown
Collaborator Author

Once this presubmit comes back maximally green (I suspect it will, but our build matrix is known to surprise me) I'm officially happy enough with this PR to bring it to our council of elders for consideration. (I'll also say that having it formally written with spray paint on a wall that I could reference over the recent N months has been super helpful to me, so thank you for humouring me.)

I've now tested/fixed/verified {Mesmerizer/Arduino V2, A demo-variant on S3 for both 'analog' (no such things) and I2S for both Arduino V2 and Arduino V3 variations. Is it every possible combination? No. But this gets us over the ArduinoV2/V3 hump, the IWYU hump, the network reorg hump, and generally brings this PR into a safe place.

I've additionally verified that the 'simbeat' feature I added relied on some uninitialized variable behavior that isn't the same on A3. That was a rookie move. (I know better. Come on C++26!) I've verified and corrected that assumption and confirmed that it works on plain old mesmerizer with plain ole mesmerizer mics on plain old Arduino v2 code that we're using today.

@robertlipe

Copy link
Copy Markdown
Collaborator Author

As a disclosure, I did the original lifting of "receive sonic waves, prepare pixels" for ESP/IDF{4,5} originally by hand a full 6+ months ago. I DID rely heavily upon Gemini (and reviews from others) to actually handle the "Oh, and pencil whip the changes for the other 53 boards for each ArduinoV2 and ArduinoV3 case" and "Pull this PR forward through the tree while some doofus scribbles all over the code in the name of IWYU, networking changes, and generally good taste."

IMO, this change is ready for the big time. I think it's fully independent from #801 but these two are our two top tenured PRs circling the airport, IMO. That's not pressure or expectation. Just saying I feel pretty comfortabable tbout these two landing first.

They can circle the airport for more weeks. That's fine. I'm just attaching a post-its that say "I think this is ready" and "I think this should go in before some others."

@robertlipe
robertlipe marked this pull request as ready for review April 8, 2026 09:39
@robertlipe

Copy link
Copy Markdown
Collaborator Author

Ooops. Some stowaways crept in. Please stand by.

Revert several stray files that had crept in.
Restore use of Allman curlies.
approximately never) that halt the DMA BEFORE we destroy the channels.

Maybe some day we'll care about power management or have an 'audio
off/audio on' in a CLI/MCP or something. If we're going to HAVE a
destructor, it should work and not leak DMA handles.

Mostly this is just good hygeine.
@robertlipe

Copy link
Copy Markdown
Collaborator Author

While cleaning up all the tagalons, I decided I really hated all the excessively clever templates and dove back in for "just one more fix".

Retested: Mesmerizer & CI now builds Arduino2 and Arduino3 targets.

Gemini's review is below. It's slightly confused about history, but since that history was 10 hours ago, meh. I implemented a fix for bullet point #1. IDC about #2. #3 is "Good Job"; TL:DR Gemini likes it in the groveling way that it does. (And I really need to start letting IT do more of this slugwork...)

I've completed my review of PR #801. Overall, this is a very high-quality modernization of the audio and network stacks. The refactoring into a base-class architecture and the addition of modern ESP-IDF 5 driver support are major improvements to the codebase's longevity and stability.

I've detailed my findings, including a few minor technical recommendations, in the review report below.

PR #801: Modern Audio & Network Refactor Review

🏆 Key Achievements

1. Audio Architecture Refactor

The transition to SoundAnalyzerBase is a significant architectural win.

  • Decoupling: Moving hardware handles and sampling logic into a non-template base class reduces code bloat and improves compile times.
  • Memory Safety: Successfully migrated to std::unique_ptr for the sample buffer, utilizing MALLOC_CAP_8BIT for PSRAM allocation—a critical fix for long-running stability.
  • Clarity: Restored the "Davepl-isms" (voodoo commentary) to ensure the institutional knowledge of the music analysis logic is preserved.

2. Hardware Modernization (IDF 5.x)

  • Future-Proofing: The addition of InitI2S_Modern and InitADC_Modern using the new ESP-IDF i2s_std and adc_continuous drivers is timely, as the original drivers were deprecated in ESP-IDF 5.0.
  • Robustness: The use of ESP_ERROR_CHECK in the modern paths ensures that hardware failures are caught early during development rather than surfacing as silent audio glitches.

3. Build System Optimization

  • PSRAM Errata Management: Refactoring platformio.ini to isolate the -mfix-esp32-psram-cache-issue flag to only affect LX6-based modules is a professional-grade optimization. This avoids performance penalties on newer chips (S2/S3/P4) that are unaffected by the errata.

4. Code Quality & Tooling

  • Internal Audits: The improvements to audit_include_rules.py are excellent. Enforcing the tiered order (Globals > System <...> > Local "...") brings the project in line with enterprise-level C++ standards.
  • Naming: Moving network utility functions into the nd_network namespace significantly cleans up the global namespace.

🔍 Technical Observations & Recommendations

While the PR is solid, there are three minor areas worth a quick look before final merge:

1. Destructor Resource Cleanup (Minor Leak)

In soundanalyzer.cpp, the destructor SoundAnalyzerBase::~SoundAnalyzerBase() currently only cleans up the legacy I2S driver.

Important

The modern _rx_handle (I2S) and _adc_handle (ADC) are currently leaked if the object is destroyed. To fix this, you should add:

#if IS_IDF5
if (_rx_handle) i2s_del_channel(_rx_handle);
if (_adc_handle) adc_continuous_del_handle(_adc_handle);
#endif

2. Frame Wait Synchronization

In network.cpp, the NetworkThread has been refactored. The logic for notifyWait = pdMS_TO_TICKS(holdMs) is cleaner, but ensure that the default holdMs = 1000 doesn't delay the first network pass on boot. (It currently waits for the first second before checking ConnectToWiFi, which is likely fine).

3. Style Polish (Formatting)

We caught the "one-liners" and the "crushed" braces in the header just in time. The current state is fully Allman-compliant and matches the rest of the project.


🟢 Verdict: RECOMMEND MERGE

After addressing (or deciding to defer) the modern handle cleanup in the destructor, this PR is ready to land. It’s a textbook example of how to refactor an organic project into a more structured and modern state without losing its history.

Excellent work! 🚀

@rbergen

rbergen commented Apr 9, 2026

Copy link
Copy Markdown
Collaborator

@robertlipe I can't really deduce from your last comment if you've heard this work?

@robertlipe

Copy link
Copy Markdown
Collaborator Author

Yes. This last version is known to work on Mesmerizer (V2), demo_v3 on an ESP32-Nothing with an analog (MAX4466) mic, and on M5 audio. That's at least close to the interesting corners of the matrix

I'll readily admit that testing every combination of underlying OS and hardware is...challenging. I'd hoped that giving this PR some public air time would get some additional testing time from the audience, but it didn't work out this way. It was -definitely- helpful to ME to have this published as a draft so I could patch in in while developing the other steps in this process, notably being able to build spectrum2_v2 and spectrum2_v3 from the same tree.

Doubling the footprint of soundanalyzer might not seem awesome, but it's a responsible way to bridge from Arduino2 to the completely different Arduino3 ESP-IDF interfaces.

I can't absolutely promise you that I've exercised every combination of Espressif's different hardware capabilities (S3 and later don't have SOC_I2S_SUPPORTS_ADC) on {V2,V3} * {ADC,I2S,M5}.

@rbergen

rbergen commented Apr 10, 2026

Copy link
Copy Markdown
Collaborator

I'll readily admit that testing every combination of underlying OS and hardware is...challenging.

That also wouldn't be a reasonable ask. I think we sort of settled on "making sure Mesmerizer works, and aiming to have seen (or heard) every code path working on at least one instance of actual hardware" in the past, and I think you're saying that's what you made a genuine effort towards.

@rbergen rbergen left a comment

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

LGTM!

@rbergen
rbergen merged commit a659b70 into PlummersSoftwareLLC:main Apr 10, 2026
52 checks passed
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.

2 participants