Repository navigation
Add DecoderSource::prepare() to allocate kept resources up front - #44
Merged
Merged
Conversation
…ader GCC's sanitizer headers are not installed on the CI image, so the include broke both sanitizer test builds. The ASan and TSan runtimes of GCC and Clang all export the function.
- Register the prepare_* tests in DECODER_TESTS; CI runs only ctest, so they never ran there. Add a tests_registered check that fails when the TESTS table and DECODER_TESTS disagree. - Add prepare_during_url_playback: prepare() mid-stream must leave a persistent ring buffer with unread data untouched. - Make the mid-playback buffer case deterministic, and require worker thread counts to hold for a settle window. - prepare() returns false without allocating when the event flags failed and a persistent option is set; document that case. - Move the prepare() docs to after the DecoderSource is created. - Correct the thread-name comment: Linux rejects names over 15 chars. - Revert unrelated reformatting in the test file.
There was a problem hiding this comment.
🟡 Changes recommended
Timeout cleanup can leave decoder callbacks accessing freed objects, while premature AudioReader construction can terminate the process on allocation failure instead of letting prepare() return false.
2 open issues
What changed in this PR
Adds optional DecoderSource::prepare() to allocate persistent resources early, helping embedded callers reduce heap fragmentation.
Changes:
- Separate worker creation from playback and retry missing persistent ring-buffer allocation.
- Name host worker threads for debugging and test observation.
- Add preparation tests, CTest registration validation, and documentation.
| File | Description |
|---|---|
tests/test_micro_decoder.cpp |
Tests preparation, resource reuse, and lifecycle behavior. |
tests/CMakeLists.txt |
Registers new tests and validates registration completeness. |
src/platform/thread.h |
Adds host thread naming. |
src/decoder_source.cpp |
Implements preparation and separates worker creation from playback. |
include/micro_decoder/types.h |
Documents preparation alongside persistence options. |
include/micro_decoder/decoder_source.h |
Declares and documents prepare(). |
docs/INTEGRATION.md |
Explains early allocation and usage. |
CLAUDE.md |
Updates the thread-lifecycle description. |
Review effort: Max (adaptive)
A failed check mid-playback returned with the decoder still running, and the listener and WAV buffer it was using were destroyed before ~DecoderSource() stopped it.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.

Adds
DecoderSource::prepare(), which allocates the resourcesDecoderConfigsays to keep at a time the caller chooses, instead of at the firstplay_url()/play_buffer().With
persistent_threadsandpersistent_ring_buffer, the reader and decoder threads (with their stacks) and the ring buffer stay allocated until theDecoderSourceis destroyed. Today the threads are created at the first playback. By then the rest of the firmware (Wi-Fi, API, other components) has allocated around them, so these long-lived blocks land wherever there is room and split the internal heap. On an ESP32 (ESPHomeaudio_http, ESP-IDF 6.1.1), the same persistent-threads build showed a largest free internal block of 61 KB after playback in one run and 110 KB in another, depending on where those allocations landed. Callingprepare()early in boot allocates them before everything else.The ESPHome caller will be
audio_http'ssetup(), together with its newpersistent_threadsoption, once a release includes this.Design
bool prepare()onDecoderSource:persistent_threads, creates both threads, parked on their start flags.persistent_ring_buffer, allocates the ring buffer if the constructor's allocation failed. The constructor already claims it, so usually there is nothing left to do.play_*()sets.true.falseand leaves the object usable. Each thread is attempted even if the other fails, and the nextplay_*()creates whatever is still missing. It is not[[nodiscard]]because failure is not fatal.prepare()then returnsfalsewithout allocating anything.launch_reader()/launch_decoder()are split intoensure_*_thread(), which creates a thread, and the hand-off of a playback.prepare()uses the first part only.play_buffer(), which never needs the reader. That costs the reader stack (6 KB in the ESPHome config) for nothing. This is documented on the method.md_reader/md_decoderwithpthread_setname_np(newset_current_thread_name()inplatform/thread.h). ESP-IDF already uses these names for the FreeRTOS tasks, and the call is a no-op there. The tests need the names (see below), and debuggers show them too.HTTP client: not pre-created
prepare()does not create the reader's HTTP client or its receive buffer. Doing it would take:HttpClient::prepare(const HttpRequest&)that builds theesp_http_clienthandle from a placeholder URL.esp_http_client_init()needs a URL or host.AudioReader::prepare()that calls it. TheAudioReaderlives on the reader thread's stack, so the reader thread would have to do this itself after it starts.prepare()would then need another event flag to wait for the result before it could report success.It would not hold up, because the handle does not keep its boot-time placement.
EspHttpClient::open()frees the handle and builds a new one:cleanup())ESP_ERR_HTTP_EAGAINheader retryreset_for()sees the URL scheme changeSo after the first unreachable server or the first http↔https switch, the handle lands wherever the heap has room at that moment, just as it does now. TLS session memory is allocated per connection either way, as the request noted. I left it out. If it's wanted, the better route is probably to have the ESP client reuse its handle on the failure paths, not to create it earlier.
Tests
Six new tests. All 48 tests, plus the registration check below, pass through
ctestunder ASan/UBSan and TSan locally. Eachprepare_*test also passed 5 repeated runs under both sanitizers.prepare_allocates_only_what_config_keeps: tries all four combinations of the two options. Constructing never starts a thread.prepare()starts one reader and one decoder exactly whenpersistent_threadsis set. With neither option set, it changes the live heap by 0 bytes. It never allocates a ring buffer, because only the constructor does that, withpersistent_ring_buffer. A playback still works afterwards, and one-shot workers are still joined.prepare_reuses_threads_and_ring_buffer: afterprepare(), three URL + buffer playback pairs. Exactly one reader and one decoder exist throughout. One decoder thread delivers all the audio (thethread_localtoken from the persistent-thread tests). One keep-alive connection carries all three URL requests, which only a single reader with a single HTTP client can do. The heap does not grow by another ring buffer.prepare_twice_and_after_play: a secondprepare()adds nothing, and neither does one after a playback. Aprepare()called during a buffer playback on a persistent decoder adds only the missing reader, and the next URL playback runs on those same two threads. The test checks that the playback is still unfinished whenprepare()runs.prepare_during_url_playback: callsprepare()(twice) during a throttled URL stream with a persistent ring buffer holding unread data. The output must stay bit-exact. Verified to fail ifprepare()resets the ring buffer.prepare_then_destroy: destroys right afterprepare()with no playback, 20 times, to give the sanitizers several chances at the window where the reader may still be setting itself up. Also covers the case with no listener ever set.prepare_then_stop: twostop()calls with nothing playing return at once, report no state change, and leave the parked threads ready for a URL and a buffer playback.Registration check. CI runs only the tests listed in
DECODER_TESTSintests/CMakeLists.txt, and the first push of this PR left the new tests out of it. A newtests_registeredctest entry runstest_micro_decoder --check-registered <DECODER_TESTS>, which fails if the binary's test table and that list disagree in either direction.How threads and memory are observed. Host thread stacks are mapped, not taken from the heap. libcurl and macOS also start worker threads of their own, which made a plain process thread count unreliable on the first attempt. The tests therefore count threads named
md_reader/md_decoder:/proc/self/task/*/common Linux,task_threads()+THREAD_EXTENDED_INFOon macOS. Ring buffer checks use__sanitizer_get_current_allocated_bytes()with a 1 MiB ring buffer, and are compiled only in sanitizer builds. Both CI test jobs are sanitizer builds. The function is declared in the test file rather than through<sanitizer/allocator_interface.h>, because GCC's sanitizer headers are not installed on the CI image. Worker-thread counts must hold for 100 ms before a check passes, so a thread created by mistake cannot slip past before it names itself.I checked that the tests can fail. With
prepare()stubbed to allocate a ring buffer and create no threads, four of the original five tests fail: on the thread counts, and on the heap check (1,142,956 vs 94,380 bytes). That run predatesprepare_during_url_playback, which has its own check above.Not covered:
PlatformThreadignores the stack size, so there is no clean way to makepthread_createfail.