Skip to content

Add DecoderSource::prepare() to allocate kept resources up front - #44

Merged
kahrendt merged 4 commits into
mainfrom
prepare-resources
Dec 4, 2026
Merged

kahrendt merged 4 commits into
mainfrom
prepare-resources

Conversation

@kahrendt

@kahrendt kahrendt commented Dec 4, 2026 •

Copy link
Copy Markdown
Contributor

Adds DecoderSource::prepare(), which allocates the resources DecoderConfig says to keep at a time the caller chooses, instead of at the first play_url() / play_buffer().

With persistent_threads and persistent_ring_buffer, the reader and decoder threads (with their stacks) and the ring buffer stay allocated until the DecoderSource is 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 (ESPHome audio_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. Calling prepare() early in boot allocates them before everything else.

The ESPHome caller will be audio_http's setup(), together with its new persistent_threads option, once a release includes this.

Design

  • bool prepare() on DecoderSource:
    • With persistent_threads, creates both threads, parked on their start flags.
    • With 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.
    • Only allocates what is not already held. Calling it twice, or after a playback, adds nothing. It never resets or frees anything, so it is also safe during a playback: a worker created then waits for a start bit that only play_*() sets.
    • With neither option set, it does nothing and returns true.
    • On failure it logs, returns false and leaves the object usable. Each thread is attempted even if the other fails, and the next play_*() creates whatever is still missing. It is not [[nodiscard]] because failure is not fatal.
    • If the constructor could not allocate the event flags, the object can never play. With a persistent option set, prepare() then returns false without allocating anything.
    • It is optional. Callers that never call it get exactly the old behaviour and memory use.
  • launch_reader() / launch_decoder() are split into ensure_*_thread(), which creates a thread, and the hand-off of a playback. prepare() uses the first part only.
  • Both threads are created even for a caller that only uses 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.
  • Host only: worker threads now name themselves md_reader / md_decoder with pthread_setname_np (new set_current_thread_name() in platform/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:

  • An HttpClient::prepare(const HttpRequest&) that builds the esp_http_client handle from a placeholder URL. esp_http_client_init() needs a URL or host.
  • An AudioReader::prepare() that calls it. The AudioReader lives 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:

  • on any failed open, header fetch or non-2xx status (cleanup())
  • on each ESP_ERR_HTTP_EAGAIN header retry
  • on a redirect that changes scheme
  • whenever reset_for() sees the URL scheme change

So 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 ctest under ASan/UBSan and TSan locally. Each prepare_* 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 when persistent_threads is 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, with persistent_ring_buffer. A playback still works afterwards, and one-shot workers are still joined.
  • prepare_reuses_threads_and_ring_buffer: after prepare(), three URL + buffer playback pairs. Exactly one reader and one decoder exist throughout. One decoder thread delivers all the audio (the thread_local token 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 second prepare() adds nothing, and neither does one after a playback. A prepare() 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 when prepare() runs.
  • prepare_during_url_playback: calls prepare() (twice) during a throttled URL stream with a persistent ring buffer holding unread data. The output must stay bit-exact. Verified to fail if prepare() resets the ring buffer.
  • prepare_then_destroy: destroys right after prepare() 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: two stop() 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_TESTS in tests/CMakeLists.txt, and the first push of this PR left the new tests out of it. A new tests_registered ctest entry runs test_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/*/comm on Linux, task_threads() + THREAD_EXTENDED_INFO on 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 predates prepare_during_url_playback, which has its own check above.

Not covered:

  • A failed thread creation. On host, PlatformThread ignores the stack size, so there is no clean way to make pthread_create fail.

…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.
@kahrendt
kahrendt marked this pull request as ready for review December 4, 2026 18:51
Copilot AI adaptive review requested due to automatic review settings December 4, 2026 18:51

Copilot AI 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.

🟡 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)

Comment thread src/decoder_source.cpp Resolved
Comment thread tests/test_micro_decoder.cpp Resolved
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.
@kahrendt
kahrendt merged commit 7a45da1 into main Dec 4, 2026
13 checks passed
@kahrendt
kahrendt deleted the prepare-resources branch December 4, 2026 19:27
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