From cb51b663ba741ae2e375c5378f0168f511919764 Mon Sep 17 00:00:00 2001 From: Kevin Ahrendt Date: Fri, 4 Dec 2026 12:01:14 -0500 Subject: [PATCH 1/4] Add DecoderSource::prepare() to allocate kept resources up front --- CLAUDE.md | 2 +- docs/INTEGRATION.md | 13 +- include/micro_decoder/decoder_source.h | 20 ++ include/micro_decoder/types.h | 5 +- src/decoder_source.cpp | 83 ++++- src/platform/thread.h | 22 ++ tests/test_micro_decoder.cpp | 420 ++++++++++++++++++++++++- 7 files changed, 535 insertions(+), 30 deletions(-) diff --git a/CLAUDE.md b/CLAUDE.md index b63bbdb..ddc53e8 100644 --- a/CLAUDE.md +++ b/CLAUDE.md @@ -19,7 +19,7 @@ DecoderSource -- public entry point (pImpl) **Data flow (buffer):** `const uint8_t* -> AudioDecoder -> DecoderListener` -By default threads are short-lived: spawned by `play_url()` / `play_buffer()`, joined by `stop()` or the destructor. With `DecoderConfig::persistent_threads` they are created on first use and park between playbacks on a start flag; `stop()` then waits on per-thread "exited" flags instead of joining, and only the destructor joins. `EventFlags` coordinate the reader and decoder threads. +By default threads are short-lived: spawned by `play_url()` / `play_buffer()`, joined by `stop()` or the destructor. With `DecoderConfig::persistent_threads` they are created on first use, or up front by `prepare()`, and park between playbacks on a start flag; `stop()` then waits on per-thread "exited" flags instead of joining, and only the destructor joins. `EventFlags` coordinate the reader and decoder threads. **Callback threading:** `on_stream_info()` and `on_audio_write()` fire on the decoder thread. `on_state_change()` fires exclusively on the caller's thread via `loop()`. Worker threads set event flags; `loop()` reads them and dispatches state callbacks. State changes from `stop()` and error paths are deferred to the next `loop()` call. diff --git a/docs/INTEGRATION.md b/docs/INTEGRATION.md index 20b39a1..24b0f5b 100644 --- a/docs/INTEGRATION.md +++ b/docs/INTEGRATION.md @@ -158,6 +158,15 @@ Threads follow the same pattern. By default each `play_*()` call creates the thr config.persistent_threads = true; ``` +Kept resources still land wherever the heap has room when they are first allocated. To choose when that is, call `prepare()` once the `DecoderSource` exists, for example at boot before the rest of the firmware allocates around it. With `persistent_threads` it creates both threads, parked until the first playback; with `persistent_ring_buffer` it allocates the ring buffer if construction could not. It is optional: without it, playback allocates on first use as before. It only allocates what is not already held, so calling it twice or after a playback does nothing more, and with neither option set it does nothing and returns `true`. On failure it logs, returns `false` and leaves the object usable; the next `play_*()` call tries again for whatever it needs. Both threads are created even if only `play_buffer()` will be used, which never needs the reader. The reader's HTTP client and receive buffer are still created by the first `play_url()`, and TLS session memory is allocated per connection: + +```cpp +DecoderSource decoder(config); +if (!decoder.prepare()) { + // Logged already; playback will retry the allocation +} +``` + On ESP-IDF, you can also configure task priorities and stack sizes: ```cpp @@ -386,8 +395,8 @@ int main() { | Field | Type | Default | Description | |---|---|---|---| | `ring_buffer_size` | `size_t` | `49152` (48 KB) | Ring buffer size in bytes between the reader and decoder threads. Larger values absorb more HTTP jitter at the cost of memory. Values below `MIN_RING_BUFFER_SIZE` (512 bytes) are raised to it, so the start of a stream always fits for format detection. | -| `persistent_ring_buffer` | `bool` | `false` | Keep the ring buffer allocated for the lifetime of the `DecoderSource`. When `false`, `play_url()` allocates it and `stop()` frees it. When `true`, it is allocated once at construction and reused, trading the memory for moving the fragmentation-sensitive allocation to construction time. A construction-time failure is logged and `play_url()` falls back to allocating on demand. A reused buffer is emptied before each playback. Buffer playback never allocates a ring buffer either way. | -| `persistent_threads` | `bool` | `false` | Keep the reader and decoder threads alive between playbacks. When `false`, each `play_*()` call creates the threads it needs and `stop()` joins them. When `true`, each thread is created the first time it is needed and then parks between playbacks until the `DecoderSource` is destroyed, removing the per-playback task creation and stack allocation at the cost of holding both stacks for the object's lifetime. Codec state is still rebuilt for every playback. | +| `persistent_ring_buffer` | `bool` | `false` | Keep the ring buffer allocated for the lifetime of the `DecoderSource`. When `false`, `play_url()` allocates it and `stop()` frees it. When `true`, it is allocated once at construction and reused, trading the memory for moving the fragmentation-sensitive allocation to construction time. A construction-time failure is logged and `prepare()` or `play_url()` retries it. A reused buffer is emptied before each playback. Buffer playback never allocates a ring buffer either way. | +| `persistent_threads` | `bool` | `false` | Keep the reader and decoder threads alive between playbacks. When `false`, each `play_*()` call creates the threads it needs and `stop()` joins them. When `true`, each thread is created the first time it is needed and then parks between playbacks until the `DecoderSource` is destroyed, removing the per-playback task creation and stack allocation at the cost of holding both stacks for the object's lifetime. Call `prepare()` to create both threads up front instead. Codec state is still rebuilt for every playback. | | `transfer_buffer_size` | `size_t` | `8192` (8 KB) | Size in bytes of the flat buffer the decoder stages decoded audio in before `on_audio_write()`. The decoder may grow it if a stream needs more. Also caps how many encoded bytes the decoder takes from the ring buffer at once. The reader keeps no staging buffer of its own: it hands ring buffer storage straight to the HTTP client. | | `http_timeout_ms` | `uint32_t` | `5000` | Timeout for one connect and header-fetch attempt, in milliseconds. A server that is slow to produce headers gets up to six attempts, so the worst case before `play_url()` fails is six times this value. On ESP-IDF each attempt is a fresh connection; on host the budget is spent waiting on one. Also bounds how long `stop()` waits while connecting, since a stop is noticed once per attempt at worst. While checking the first body bytes for the format, the reader gives up waiting after this long without any new data and goes by the headers. On host (libcurl), a stream that stops delivering data fails once it has stayed below 1 byte/s for six times this value (30 s by default), rounded up to whole seconds; `0` turns this check off. | | `http_read_timeout_ms` | `uint32_t` | `500` | Maximum time a single HTTP body read may block, in milliseconds, applied once the headers have arrived. Bounds how long `stop()` waits for the reader thread while a stream is running, since it can only observe a stop request between reads. No effect on host, where reads do not block. | diff --git a/include/micro_decoder/decoder_source.h b/include/micro_decoder/decoder_source.h index 0dfe426..a551a60 100644 --- a/include/micro_decoder/decoder_source.h +++ b/include/micro_decoder/decoder_source.h @@ -83,6 +83,26 @@ class DecoderSource { DecoderSource(DecoderSource&&) = delete; DecoderSource& operator=(DecoderSource&&) = delete; + /// @brief Allocates the resources the config keeps for this object's lifetime, now + /// rather than at the first play_url() or play_buffer() + /// With DecoderConfig::persistent_threads this creates the reader and decoder threads + /// (with their stacks), parked until a playback is handed to them. With + /// DecoderConfig::persistent_ring_buffer it allocates the ring buffer, unless the + /// constructor already did. Call it early, for example at boot before other components + /// allocate, so these long-lived blocks do not land between shorter-lived ones and split + /// the heap. + /// @note Optional. Without it, play_url() and play_buffer() allocate on first use as + /// usual. Only what is not already held is allocated, so calling it again, or after a + /// playback, does nothing more. With neither persistent option set it does nothing. + /// @note Both threads are created, even if only play_buffer() will be used, which never + /// needs the reader. + /// @note The reader's HTTP client is not created here; it is still built on the first + /// play_url(). + /// @return true if everything the config keeps is now allocated, including when there is + /// nothing to keep. false if an allocation failed; the object stays usable, and the next + /// play_url() or play_buffer() tries again for whatever it needs. + bool prepare(); + /// @brief Sets the listener that receives decoded PCM and state change events /// @note Must be called before play_url() or play_buffer(). Must not be called while /// playback is active. The listener must remain valid until stop() returns or the decoder diff --git a/include/micro_decoder/types.h b/include/micro_decoder/types.h index c5f4ac0..a64b5aa 100644 --- a/include/micro_decoder/types.h +++ b/include/micro_decoder/types.h @@ -337,7 +337,7 @@ struct DecoderConfig { /// logged and play_url() falls back to allocating on demand, carrying the same /// fragmentation risk as the false case for that playback. A reused buffer is emptied /// before each playback either way. Buffer-sourced playback never allocates a ring - /// buffer. + /// buffer. DecoderSource::prepare() also retries a failed construction-time allocation. bool persistent_ring_buffer{false}; /// @brief Keep the reader and decoder threads alive between playbacks @@ -349,7 +349,8 @@ struct DecoderConfig { /// transient allocation in a play/stop cycle, in exchange for holding both stacks for /// the object's lifetime. Playback behaviour is otherwise identical: codec state is /// still built fresh for every playback, and stop() still blocks until both threads - /// have finished with the current one. + /// have finished with the current one. Call DecoderSource::prepare() to create both + /// threads up front rather than at the first playback. bool persistent_threads{false}; // ======================================== diff --git a/src/decoder_source.cpp b/src/decoder_source.cpp index 6ab6b0f..4b4e728 100644 --- a/src/decoder_source.cpp +++ b/src/decoder_source.cpp @@ -31,6 +31,10 @@ namespace micro_decoder { static constexpr const char* TAG = "micro_decoder.decoder_source"; +// Worker thread names: the FreeRTOS task names on ESP-IDF, the pthread names on host +static constexpr const char* READER_THREAD_NAME = "md_reader"; +static constexpr const char* DECODER_THREAD_NAME = "md_decoder"; + // ============================================================================ // Event flag bits // ============================================================================ @@ -153,6 +157,39 @@ struct DecoderSource::Impl { return this->ring_buffer.create(this->config.ring_buffer_size); } + /// @brief Allocates whatever the config keeps for the object's lifetime and is not yet held + /// The ring buffer when persistent_ring_buffer is set, and both worker threads, parked on + /// their start flags, when persistent_threads is set. Never resets or frees anything, so + /// it is safe while a playback is active: a held ring buffer is left as is, and a worker + /// created here waits for a start bit that only play_*() sets. + /// @return true if everything the config keeps is now held + bool prepare() { + bool ok = true; + if (this->config.persistent_ring_buffer && !this->ring_buffer.allocated()) { + if (!this->ring_buffer.create(this->config.ring_buffer_size)) { + MD_LOGW(TAG, "Failed to allocate the ring buffer; will retry on playback"); + ok = false; + } + } + if (this->config.persistent_threads) { + // A worker without event flags could never be handed a playback or told to exit + if (!this->initialized_) { + MD_LOGE(TAG, "Not initialized (event flags allocation failed)"); + return false; + } + // Each is attempted even if the other fails; play_*() creates whatever is missing + if (!this->ensure_reader_thread()) { + MD_LOGW(TAG, "Failed to create the reader thread; will retry on playback"); + ok = false; + } + if (!this->ensure_decoder_thread()) { + MD_LOGW(TAG, "Failed to create the decoder thread; will retry on playback"); + ok = false; + } + } + return ok; + } + /// @brief Frees the ring buffer unless it is configured to persist /// @note Both workers must have reported the playback done first; they read and write /// the ring buffer. @@ -240,16 +277,34 @@ struct DecoderSource::Impl { this->ring_buffer.wake_writer(); } + /// @brief Makes sure a reader thread exists, parked until a playback is handed to it + /// @return false if no thread is alive and one could not be created + bool ensure_reader_thread() { + if (this->reader_thread.joinable()) { + return true; + } + // Always in internal RAM for lwip settings compatibility + ThreadConfig cfg{READER_THREAD_NAME, this->config.reader_stack_size, + this->config.reader_priority, false}; + return this->reader_thread.start(cfg, &Impl::reader_entry, this); + } + + /// @brief Makes sure a decoder thread exists, parked until a playback is handed to it + /// @return false if no thread is alive and one could not be created + bool ensure_decoder_thread() { + if (this->decoder_thread.joinable()) { + return true; + } + ThreadConfig cfg{DECODER_THREAD_NAME, this->config.decoder_stack_size, + this->config.decoder_priority, this->config.decoder_stack_in_psram}; + return this->decoder_thread.start(cfg, &Impl::decoder_entry, this); + } + /// @brief Makes sure a reader thread exists and hands it the playback in this->url /// @return false if no thread is alive and one could not be created bool launch_reader() { - if (!this->reader_thread.joinable()) { - // Always in internal RAM for lwip settings compatibility - ThreadConfig cfg{"md_reader", this->config.reader_stack_size, - this->config.reader_priority, false}; - if (!this->reader_thread.start(cfg, &Impl::reader_entry, this)) { - return false; - } + if (!this->ensure_reader_thread()) { + return false; } this->reader_active_ = true; this->event_flags.set(FLAG_READER_START); @@ -259,12 +314,8 @@ struct DecoderSource::Impl { /// @brief Makes sure a decoder thread exists and hands it the active playback /// @return false if no thread is alive and one could not be created bool launch_decoder() { - if (!this->decoder_thread.joinable()) { - ThreadConfig cfg{"md_decoder", this->config.decoder_stack_size, - this->config.decoder_priority, this->config.decoder_stack_in_psram}; - if (!this->decoder_thread.start(cfg, &Impl::decoder_entry, this)) { - return false; - } + if (!this->ensure_decoder_thread()) { + return false; } this->decoder_active_ = true; this->event_flags.set(FLAG_DECODER_START); @@ -317,6 +368,7 @@ struct DecoderSource::Impl { /// @param arg Pointer to the owning Impl /// @return Always nullptr; the result is unused static void* reader_entry(void* arg) { + set_current_thread_name(READER_THREAD_NAME); static_cast(arg)->reader_thread_main(); return nullptr; } @@ -412,6 +464,7 @@ struct DecoderSource::Impl { /// @param arg Pointer to the owning Impl /// @return Always nullptr; the result is unused static void* decoder_entry(void* arg) { + set_current_thread_name(DECODER_THREAD_NAME); static_cast(arg)->decoder_thread_main(); return nullptr; } @@ -579,6 +632,10 @@ DecoderSource::~DecoderSource() { this->impl_->shutdown_threads(); } +bool DecoderSource::prepare() { + return this->impl_->prepare(); +} + void DecoderSource::set_listener(DecoderListener* listener) { this->impl_->listener.store(listener, std::memory_order_release); } diff --git a/src/platform/thread.h b/src/platform/thread.h index 6784c83..edc3d38 100644 --- a/src/platform/thread.h +++ b/src/platform/thread.h @@ -47,6 +47,7 @@ static constexpr const char* THREAD_TAG = "micro_decoder.thread"; /// @note Every field except name is ignored on host, where the OS defaults are used. struct ThreadConfig { /// @brief Thread name, used for FreeRTOS task naming (ESP-IDF only) + /// On host the thread names itself with set_current_thread_name() instead. const char* name{nullptr}; /// @brief Stack size in bytes (ESP-IDF only) @@ -235,4 +236,25 @@ class PlatformThread { bool started_{false}; }; +// ============================================================================ +// Thread naming +// ============================================================================ + +/// @brief Names the calling thread, for debuggers and the OS's thread listings +/// A no-op on ESP-IDF, where PlatformThread::start() already names the FreeRTOS task. On +/// host it is called from the thread itself, the only way macOS allows; names longer than +/// 15 characters are truncated on Linux. +/// @param name Thread name +inline void set_current_thread_name(const char* name) { +#if defined(ESP_PLATFORM) + (void)name; +#elif defined(__APPLE__) + pthread_setname_np(name); +#elif defined(__linux__) + pthread_setname_np(pthread_self(), name); +#else + (void)name; +#endif +} + } // namespace micro_decoder diff --git a/tests/test_micro_decoder.cpp b/tests/test_micro_decoder.cpp index a3ce417..6d39647 100644 --- a/tests/test_micro_decoder.cpp +++ b/tests/test_micro_decoder.cpp @@ -43,14 +43,32 @@ #include "md_transfer_buffer.h" #include "platform/event_flags.h" #include "ring_buffer.h" - #include +#include #include #include #include // setenv() is POSIX, so not guaranteed by #include #include +#ifdef __APPLE__ +#include +#endif + +// The sanitizer runtimes count the bytes the program has live on the heap, which lets the +// prepare() tests see whether a ring buffer was allocated. Both CI test jobs run under a +// sanitizer; other builds skip those checks. +#if defined(__SANITIZE_ADDRESS__) || defined(__SANITIZE_THREAD__) +#define MD_TEST_HEAP_STATS 1 +#elif defined(__has_feature) +#if __has_feature(address_sanitizer) || __has_feature(thread_sanitizer) +#define MD_TEST_HEAP_STATS 1 +#endif +#endif +#ifdef MD_TEST_HEAP_STATS +#include +#endif + #include #include #include @@ -167,13 +185,13 @@ static std::vector make_wav(uint8_t channels, uint32_t sample_rate, siz static std::vector make_ogg_page(const std::vector& first_packet) { std::vector page; page.insert(page.end(), {'O', 'g', 'g', 'S'}); - page.push_back(0); // stream structure version - page.push_back(0x02); // header type: beginning of stream - page.insert(page.end(), 8, 0); // granule position - push_u32le(page, 0x1D0DECAF); // serial number - push_u32le(page, 0); // page sequence number - push_u32le(page, 0); // CRC (not validated by detection) - page.push_back(1); // segment count + page.push_back(0); // stream structure version + page.push_back(0x02); // header type: beginning of stream + page.insert(page.end(), 8, 0); // granule position + push_u32le(page, 0x1D0DECAF); // serial number + push_u32le(page, 0); // page sequence number + push_u32le(page, 0); // CRC (not validated by detection) + page.push_back(1); // segment count page.push_back(static_cast(first_packet.size())); // lacing value page.insert(page.end(), first_packet.begin(), first_packet.end()); return page; @@ -784,8 +802,8 @@ static bool test_detect_content_short_buffers() { } CHECK(detect_prefix(opus, 26) == AudioFileType::NONE); CHECK(detect_prefix(opus, 27) == AudioFileType::NONE); - CHECK(detect_prefix(opus, 28 + 4) == AudioFileType::NONE); // "Opus" only - CHECK(detect_prefix(opus, 28 + 8) == AudioFileType::OPUS); // full magic + CHECK(detect_prefix(opus, 28 + 4) == AudioFileType::NONE); // "Opus" only + CHECK(detect_prefix(opus, 28 + 8) == AudioFileType::OPUS); // full magic // Header claiming a 200-entry segment table but truncated inside it std::vector truncated(opus.begin(), opus.begin() + 27); @@ -1444,8 +1462,7 @@ static bool test_play_buffer_passthrough() { size_t frames; }; const Case cases[] = { - {2, 44100, 4096}, - {1, 22050, 3333}, // odd frame count, mono + {2, 44100, 4096}, {1, 22050, 3333}, // odd frame count, mono }; for (const Case& c : cases) { @@ -2718,6 +2735,380 @@ static bool test_persistent_threads_reader_reuses_connection() { return true; } +// ============================================================================ +// DecoderSource: prepare() +// ============================================================================ + +/// @brief Counts this process's threads named like the library's workers +/// Host thread stacks are mapped rather than taken from the heap, and libcurl and the OS +/// start threads of their own, so counting the workers by name is how these tests see one +/// being created or joined. +/// @return false where thread names cannot be read +static bool count_worker_threads(size_t& readers, size_t& decoders) { + readers = 0; + decoders = 0; + auto tally = [&](const char* name) { + if (std::strcmp(name, "md_reader") == 0) { + ++readers; + } else if (std::strcmp(name, "md_decoder") == 0) { + ++decoders; + } + }; +#if defined(__APPLE__) + thread_act_array_t threads = nullptr; + mach_msg_type_number_t count = 0; + if (task_threads(mach_task_self(), &threads, &count) != KERN_SUCCESS) { + return false; + } + for (mach_msg_type_number_t i = 0; i < count; ++i) { + thread_extended_info_data_t info{}; + mach_msg_type_number_t info_count = THREAD_EXTENDED_INFO_COUNT; + if (thread_info(threads[i], THREAD_EXTENDED_INFO, reinterpret_cast(&info), + &info_count) == KERN_SUCCESS) { + tally(info.pth_name); + } + mach_port_deallocate(mach_task_self(), threads[i]); + } + vm_deallocate(mach_task_self(), reinterpret_cast(threads), + count * sizeof(thread_act_t)); + return true; +#elif defined(__linux__) + DIR* dir = opendir("/proc/self/task"); + if (dir == nullptr) { + return false; + } + while (const dirent* entry = readdir(dir)) { + if (entry->d_name[0] == '.') { + continue; + } + std::string path = std::string("/proc/self/task/") + entry->d_name + "/comm"; + FILE* f = std::fopen(path.c_str(), "r"); + if (f == nullptr) { + continue; // the thread exited while listing + } + char name[32] = {}; + if (std::fgets(name, sizeof(name), f) != nullptr) { + name[std::strcspn(name, "\n")] = '\0'; + tally(name); + } + std::fclose(f); + } + closedir(dir); + return true; +#else + return false; +#endif +} + +/// @brief Waits for exactly this many reader and decoder threads to be running +/// A new thread names itself once it runs, and a joined one can take a moment to leave the +/// OS's list, so this polls briefly. +/// @return true if the counts matched, or if thread names cannot be read here +static bool wait_worker_threads(size_t readers, size_t decoders) { + size_t r = 0; + size_t d = 0; + uint64_t deadline = now_ms() + 2000; + do { + // cppcheck-suppress knownConditionTrueFalse // false only off macOS and Linux + if (!count_worker_threads(r, d)) { + return true; + } + if (r == readers && d == decoders) { + return true; + } + std::this_thread::sleep_for(std::chrono::milliseconds(5)); + } while (now_ms() < deadline); + std::printf(" expected %zu reader / %zu decoder threads, have %zu / %zu\n", readers, + decoders, r, d); + return false; +} + +/// @brief Returns the bytes the program has live on the heap, or 0 without a sanitizer +static size_t heap_bytes() { +#ifdef MD_TEST_HEAP_STATS + return __sanitizer_get_current_allocated_bytes(); +#else + return 0; +#endif +} + +/// @brief Large enough that a ring buffer stands out from every other allocation +static constexpr size_t PREPARE_RING_BUFFER_SIZE = 1024 * 1024; + +static bool check_prepare_allocations(bool persistent_threads, bool persistent_ring_buffer) { + std::printf(" persistent_threads=%d persistent_ring_buffer=%d\n", persistent_threads, + persistent_ring_buffer); + DecoderConfig config; + config.persistent_threads = persistent_threads; + config.persistent_ring_buffer = persistent_ring_buffer; + config.ring_buffer_size = PREPARE_RING_BUFFER_SIZE; + + size_t heap_before_construct = heap_bytes(); + const size_t workers = persistent_threads ? 1 : 0; + DecoderSource src(config); + // Construction itself starts no threads, with or without prepare() to follow + CHECK(wait_worker_threads(0, 0)); + size_t heap_before_prepare = heap_bytes(); +#ifdef MD_TEST_HEAP_STATS + // A persistent ring buffer is still claimed at construction, as before prepare() existed + CHECK_EQ(heap_before_prepare - heap_before_construct >= PREPARE_RING_BUFFER_SIZE, + persistent_ring_buffer); +#else + (void)heap_before_construct; +#endif + + CHECK(src.prepare()); + CHECK(wait_worker_threads(workers, workers)); +#ifdef MD_TEST_HEAP_STATS + if (!persistent_threads) { + // Nothing to create: not a single byte, and certainly no ring buffer + CHECK_EQ(heap_bytes(), heap_before_prepare); + } else { + // The workers allocate a little as they start, but no ring buffer + CHECK(heap_bytes() < heap_before_prepare + PREPARE_RING_BUFFER_SIZE / 2); + } +#else + (void)heap_before_prepare; +#endif + + // Playback still works, and one-shot workers are still joined after it + std::vector payload; + std::vector wav = make_wav(2, 44100, 1024, &payload); + CaptureListener listener; + src.set_listener(&listener); + CHECK(src.play_buffer(wav.data(), wav.size(), AudioFileType::WAV)); + CHECK(pump_to_completion(src, listener)); + CHECK(listener.pcm() == payload); + src.stop(); + CHECK(wait_worker_threads(workers, workers)); + return true; +} + +static bool test_prepare_allocates_only_what_config_keeps() { + // prepare() allocates what the persistent options say to keep and nothing else. With + // neither option it must not start a thread or allocate a byte; with only + // persistent_ring_buffer the constructor already holds the buffer, so it adds nothing. + CHECK(check_prepare_allocations(false, false)); + CHECK(check_prepare_allocations(false, true)); + CHECK(check_prepare_allocations(true, false)); + CHECK(check_prepare_allocations(true, true)); + return true; +} + +static bool test_prepare_reuses_threads_and_ring_buffer() { + // The threads prepare() creates must be the ones every later playback runs on: exactly + // one reader and one decoder exist from prepare() on, one decoder thread + // delivers all the audio, and one keep-alive connection carries every URL playback, + // which only a single reader (and so a single HTTP client) can do. The ring buffer + // is the one held since construction: the heap does not grow by another one. + DecoderConfig config; + config.persistent_threads = true; + config.persistent_ring_buffer = true; + config.ring_buffer_size = PREPARE_RING_BUFFER_SIZE; + + std::vector payload_url; + TestHttpServer::Response resp; + resp.content_type = "audio/wav"; + resp.body = make_wav(2, 44100, 4096, &payload_url, 0x12345678); + resp.chunk_size = 1024; + resp.keep_alive = true; + TestHttpServer server; + CHECK(server.start(resp)); + + std::vector payload_buf; + std::vector wav = make_wav(1, 8000, 1000, &payload_buf, 0x9ABCDEF0); + + ThreadIdListener listener; + DecoderSource src(config); + src.set_listener(&listener); + CHECK(src.prepare()); + CHECK(wait_worker_threads(1, 1)); + size_t heap_after_prepare = heap_bytes(); + + static constexpr int ROUNDS = 3; + for (int round = 0; round < ROUNDS; ++round) { + listener.reset_capture(); + CHECK(src.play_url(server.url("/stream"))); + CHECK(pump_to_completion(src, listener)); + CHECK(!listener.saw_state(DecoderState::FAILED)); + CHECK(listener.pcm() == payload_url); + CHECK(wait_worker_threads(1, 1)); + + listener.reset_capture(); + CHECK(src.play_buffer(wav.data(), wav.size(), AudioFileType::WAV)); + CHECK(pump_to_completion(src, listener)); + CHECK(listener.pcm() == payload_buf); + CHECK(wait_worker_threads(1, 1)); + } + src.stop(); + + CHECK_EQ(listener.distinct_decoder_threads(), 1u); + CHECK_EQ(server.requests(), ROUNDS); + CHECK_EQ(server.connections(), 1); +#ifdef MD_TEST_HEAP_STATS + CHECK(heap_bytes() < heap_after_prepare + PREPARE_RING_BUFFER_SIZE / 2); +#else + (void)heap_after_prepare; +#endif + + server.stop(); + return true; +} + +static bool test_prepare_twice_and_after_play() { + // A second prepare(), or one after a playback, creates only what is missing. A + // persistent decoder created by play_buffer() gets its reader from a prepare() called + // mid-playback, and the next URL playback runs on those same two threads. + DecoderConfig config; + config.persistent_threads = true; + config.persistent_ring_buffer = true; + config.ring_buffer_size = PREPARE_RING_BUFFER_SIZE; + + std::vector payload_url; + TestHttpServer::Response resp; + resp.content_type = "audio/wav"; + resp.body = make_wav(2, 44100, 2048, &payload_url, 0x0F0F0F0F); + TestHttpServer server; + CHECK(server.start(resp)); + + std::vector payload_buf; + std::vector wav = make_wav(2, 44100, 1024, &payload_buf, 0xF0F0F0F0); + + { + // Twice before any playback + ThreadIdListener listener; + DecoderSource src(config); + src.set_listener(&listener); + CHECK(src.prepare()); + CHECK(wait_worker_threads(1, 1)); + size_t heap_after_first = heap_bytes(); + CHECK(src.prepare()); + CHECK(wait_worker_threads(1, 1)); +#ifdef MD_TEST_HEAP_STATS + CHECK(heap_bytes() < heap_after_first + PREPARE_RING_BUFFER_SIZE / 2); +#else + (void)heap_after_first; +#endif + CHECK(src.play_buffer(wav.data(), wav.size(), AudioFileType::WAV)); + CHECK(pump_to_completion(src, listener)); + CHECK(listener.pcm() == payload_buf); + CHECK(src.prepare()); + CHECK(wait_worker_threads(1, 1)); + CHECK_EQ(listener.distinct_decoder_threads(), 1u); + } + CHECK(wait_worker_threads(0, 0)); + + { + // After a buffer playback has created only the decoder, while a second one is playing + ThreadIdListener listener; + DecoderSource src(config); + src.set_listener(&listener); + CHECK(src.play_buffer(wav.data(), wav.size(), AudioFileType::WAV)); + CHECK(pump_to_completion(src, listener)); + CHECK(wait_worker_threads(0, 1)); + + listener.reset_capture(); + listener.max_consume = 256; // keep this playback going while prepare() runs + listener.consume_delay_ms = 1; + CHECK(src.play_buffer(wav.data(), wav.size(), AudioFileType::WAV)); + CHECK(src.prepare()); + CHECK(wait_worker_threads(1, 1)); + CHECK(pump_to_completion(src, listener)); + CHECK(!listener.saw_state(DecoderState::FAILED)); + CHECK(listener.pcm() == payload_buf); + + listener.reset_capture(); + listener.max_consume = SIZE_MAX; + listener.consume_delay_ms = 0; + CHECK(src.play_url(server.url("/stream"))); + CHECK(pump_to_completion(src, listener)); + CHECK(!listener.saw_state(DecoderState::FAILED)); + CHECK(listener.pcm() == payload_url); + CHECK(wait_worker_threads(1, 1)); + CHECK_EQ(listener.distinct_decoder_threads(), 1u); + } + CHECK(wait_worker_threads(0, 0)); + + server.stop(); + return true; +} + +static bool test_prepare_then_destroy() { + // Destroying right after prepare(), with no playback ever handed to the workers, must + // shut both down cleanly, including while the reader may still be setting itself up. + // Repeated to give the sanitizers several chances at that window. + DecoderConfig config; + config.persistent_threads = true; + config.persistent_ring_buffer = true; + + for (int i = 0; i < 20; ++i) { + CaptureListener listener; + { + DecoderSource src(config); + src.set_listener(&listener); + CHECK(src.prepare()); + } + CHECK(wait_worker_threads(0, 0)); + CHECK(listener.states.empty()); + } + + // Without a listener ever set, too + { + DecoderSource src(config); + CHECK(src.prepare()); + } + CHECK(wait_worker_threads(0, 0)); + return true; +} + +static bool test_prepare_then_stop() { + // stop() with nothing playing after prepare() must leave the parked workers alone, + // report no state change, and leave them ready for the next playback. + DecoderConfig config; + config.persistent_threads = true; + + std::vector payload_url; + TestHttpServer::Response resp; + resp.content_type = "audio/wav"; + resp.body = make_wav(2, 44100, 2048, &payload_url, 0x55AA55AA); + TestHttpServer server; + CHECK(server.start(resp)); + + std::vector payload_buf; + std::vector wav = make_wav(1, 22050, 1500, &payload_buf, 0xAA55AA55); + + ThreadIdListener listener; + DecoderSource src(config); + src.set_listener(&listener); + CHECK(src.prepare()); + CHECK(wait_worker_threads(1, 1)); + + uint64_t start = now_ms(); + src.stop(); + src.stop(); + CHECK(now_ms() - start < 1000); + src.loop(); + CHECK(listener.states.empty()); + CHECK(src.state() == DecoderState::IDLE); + CHECK(wait_worker_threads(1, 1)); + + CHECK(src.play_url(server.url("/stream"))); + CHECK(pump_to_completion(src, listener)); + CHECK(!listener.saw_state(DecoderState::FAILED)); + CHECK(listener.pcm() == payload_url); + + listener.reset_capture(); + CHECK(src.play_buffer(wav.data(), wav.size(), AudioFileType::WAV)); + CHECK(pump_to_completion(src, listener)); + CHECK(listener.pcm() == payload_buf); + + CHECK(wait_worker_threads(1, 1)); + CHECK_EQ(listener.distinct_decoder_threads(), 1u); + + server.stop(); + return true; +} + static const TestCase TESTS[] = { {"detect_content_type", test_detect_content_type}, {"detect_url_extension", test_detect_url_extension}, @@ -2765,6 +3156,11 @@ static const TestCase TESTS[] = { test_persistent_threads_reader_recovers_after_failure}, {"persistent_threads_reader_reuses_connection", test_persistent_threads_reader_reuses_connection}, + {"prepare_allocates_only_what_config_keeps", test_prepare_allocates_only_what_config_keeps}, + {"prepare_reuses_threads_and_ring_buffer", test_prepare_reuses_threads_and_ring_buffer}, + {"prepare_twice_and_after_play", test_prepare_twice_and_after_play}, + {"prepare_then_destroy", test_prepare_then_destroy}, + {"prepare_then_stop", test_prepare_then_stop}, }; int main(int argc, char* argv[]) { From e7f4a795ff6c2eaae522c7697e7b15d563ab4663 Mon Sep 17 00:00:00 2001 From: Kevin Ahrendt Date: Fri, 4 Dec 2026 13:16:29 -0500 Subject: [PATCH 2/4] Declare the sanitizer heap-stats function instead of including its header 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. --- tests/test_micro_decoder.cpp | 5 ++++- 1 file changed, 4 insertions(+), 1 deletion(-) diff --git a/tests/test_micro_decoder.cpp b/tests/test_micro_decoder.cpp index 6d39647..9cadf42 100644 --- a/tests/test_micro_decoder.cpp +++ b/tests/test_micro_decoder.cpp @@ -66,7 +66,10 @@ #endif #endif #ifdef MD_TEST_HEAP_STATS -#include +// Declared here rather than through : the ASan and TSan +// runtimes of both GCC and Clang export it, but GCC's sanitizer headers are not always +// installed alongside its runtimes (they are missing on the CI image). +extern "C" size_t __sanitizer_get_current_allocated_bytes(); #endif #include From 036d16c64b233e6f9e6e0b4b85059a538455b50f Mon Sep 17 00:00:00 2001 From: Kevin Ahrendt Date: Fri, 4 Dec 2026 13:43:25 -0500 Subject: [PATCH 3/4] Address review: register prepare tests with ctest and tighten them - 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. --- docs/INTEGRATION.md | 19 ++-- include/micro_decoder/decoder_source.h | 4 +- src/decoder_source.cpp | 14 +-- src/platform/thread.h | 4 +- tests/CMakeLists.txt | 10 +++ tests/test_micro_decoder.cpp | 116 +++++++++++++++++++++---- 6 files changed, 135 insertions(+), 32 deletions(-) diff --git a/docs/INTEGRATION.md b/docs/INTEGRATION.md index 24b0f5b..c5087aa 100644 --- a/docs/INTEGRATION.md +++ b/docs/INTEGRATION.md @@ -158,14 +158,7 @@ Threads follow the same pattern. By default each `play_*()` call creates the thr config.persistent_threads = true; ``` -Kept resources still land wherever the heap has room when they are first allocated. To choose when that is, call `prepare()` once the `DecoderSource` exists, for example at boot before the rest of the firmware allocates around it. With `persistent_threads` it creates both threads, parked until the first playback; with `persistent_ring_buffer` it allocates the ring buffer if construction could not. It is optional: without it, playback allocates on first use as before. It only allocates what is not already held, so calling it twice or after a playback does nothing more, and with neither option set it does nothing and returns `true`. On failure it logs, returns `false` and leaves the object usable; the next `play_*()` call tries again for whatever it needs. Both threads are created even if only `play_buffer()` will be used, which never needs the reader. The reader's HTTP client and receive buffer are still created by the first `play_url()`, and TLS session memory is allocated per connection: - -```cpp -DecoderSource decoder(config); -if (!decoder.prepare()) { - // Logged already; playback will retry the allocation -} -``` +To allocate kept resources before the first playback, for example at boot, see [Allocating Kept Resources Up Front](#allocating-kept-resources-up-front). On ESP-IDF, you can also configure task priorities and stack sizes: @@ -189,6 +182,16 @@ decoder.set_listener(&sink); // Must outlive the decoder `DecoderSource` is non-copyable and non-movable. The listener must remain valid until `stop()` returns or the decoder is destroyed. +### Allocating Kept Resources Up Front + +With `persistent_threads` or `persistent_ring_buffer` set (see Step 2), the kept threads and ring buffer land wherever the heap has room when they are first allocated. To choose when that is, call `prepare()` once the `DecoderSource` is constructed, for example at boot before the rest of the firmware allocates around it. With `persistent_threads` it creates both threads, parked until the first playback; with `persistent_ring_buffer` it allocates the ring buffer if construction could not. It is optional: without it, playback allocates on first use as before. It only allocates what is not already held, so calling it twice or after a playback does nothing more, and with neither option set it does nothing and returns `true`. On failure it logs, returns `false` and leaves the object usable; the next `play_*()` call tries again for whatever it needs. The exception is a `DecoderSource` whose constructor could not allocate its event flags: it can never play, so `prepare()` returns `false` without allocating anything, and every `play_*()` call fails too. Both threads are created even if only `play_buffer()` will be used, which never needs the reader. The reader's HTTP client and receive buffer are still created by the first `play_url()`, and TLS session memory is allocated per connection: + +```cpp +if (!decoder.prepare()) { + // Logged already; playback will retry the allocation +} +``` + ## Step 4: Play a URL or Buffer ### Streaming from a URL diff --git a/include/micro_decoder/decoder_source.h b/include/micro_decoder/decoder_source.h index a551a60..cfba961 100644 --- a/include/micro_decoder/decoder_source.h +++ b/include/micro_decoder/decoder_source.h @@ -100,7 +100,9 @@ class DecoderSource { /// play_url(). /// @return true if everything the config keeps is now allocated, including when there is /// nothing to keep. false if an allocation failed; the object stays usable, and the next - /// play_url() or play_buffer() tries again for whatever it needs. + /// play_url() or play_buffer() tries again for whatever it needs. Also false, with nothing + /// allocated, if the constructor could not allocate the event flags: such an object can + /// never play, and every play_*() call fails as well. bool prepare(); /// @brief Sets the listener that receives decoded PCM and state change events diff --git a/src/decoder_source.cpp b/src/decoder_source.cpp index 4b4e728..b35e9ca 100644 --- a/src/decoder_source.cpp +++ b/src/decoder_source.cpp @@ -164,6 +164,15 @@ struct DecoderSource::Impl { /// created here waits for a start bit that only play_*() sets. /// @return true if everything the config keeps is now held bool prepare() { + if (!this->config.persistent_ring_buffer && !this->config.persistent_threads) { + return true; + } + // Without event flags nothing can ever play, and a worker could never be handed a + // playback or told to exit, so there is nothing worth allocating + if (!this->initialized_) { + MD_LOGE(TAG, "Not initialized (event flags allocation failed)"); + return false; + } bool ok = true; if (this->config.persistent_ring_buffer && !this->ring_buffer.allocated()) { if (!this->ring_buffer.create(this->config.ring_buffer_size)) { @@ -172,11 +181,6 @@ struct DecoderSource::Impl { } } if (this->config.persistent_threads) { - // A worker without event flags could never be handed a playback or told to exit - if (!this->initialized_) { - MD_LOGE(TAG, "Not initialized (event flags allocation failed)"); - return false; - } // Each is attempted even if the other fails; play_*() creates whatever is missing if (!this->ensure_reader_thread()) { MD_LOGW(TAG, "Failed to create the reader thread; will retry on playback"); diff --git a/src/platform/thread.h b/src/platform/thread.h index edc3d38..65d10e5 100644 --- a/src/platform/thread.h +++ b/src/platform/thread.h @@ -242,8 +242,8 @@ class PlatformThread { /// @brief Names the calling thread, for debuggers and the OS's thread listings /// A no-op on ESP-IDF, where PlatformThread::start() already names the FreeRTOS task. On -/// host it is called from the thread itself, the only way macOS allows; names longer than -/// 15 characters are truncated on Linux. +/// host it is called from the thread itself, the only way macOS allows. Keep names to 15 +/// characters: Linux rejects longer ones and leaves the thread unnamed. /// @param name Thread name inline void set_current_thread_name(const char* name) { #if defined(ESP_PLATFORM) diff --git a/tests/CMakeLists.txt b/tests/CMakeLists.txt index b28f652..2bf1303 100644 --- a/tests/CMakeLists.txt +++ b/tests/CMakeLists.txt @@ -123,6 +123,12 @@ set(DECODER_TESTS persistent_threads_stop_and_destroy persistent_threads_reader_recovers_after_failure persistent_threads_reader_reuses_connection + prepare_allocates_only_what_config_keeps + prepare_reuses_threads_and_ring_buffer + prepare_twice_and_after_play + prepare_during_url_playback + prepare_then_destroy + prepare_then_stop ) foreach(test_name IN LISTS DECODER_TESTS) @@ -131,3 +137,7 @@ foreach(test_name IN LISTS DECODER_TESTS) # regression that hangs a thread join can never wedge CI. set_tests_properties(${test_name} PROPERTIES TIMEOUT 120) endforeach() + +# Fails if a test in the binary's table is missing from DECODER_TESTS (or the other way +# round), since CI runs only what is registered here +add_test(NAME tests_registered COMMAND test_micro_decoder --check-registered ${DECODER_TESTS}) diff --git a/tests/test_micro_decoder.cpp b/tests/test_micro_decoder.cpp index 9cadf42..26e3031 100644 --- a/tests/test_micro_decoder.cpp +++ b/tests/test_micro_decoder.cpp @@ -33,6 +33,7 @@ * download after the decoder thread exited). * * Usage: test_micro_decoder [test_name] + * test_micro_decoder --check-registered */ #include "micro_decoder/decoder_source.h" @@ -43,6 +44,7 @@ #include "md_transfer_buffer.h" #include "platform/event_flags.h" #include "ring_buffer.h" + #include #include #include @@ -188,13 +190,13 @@ static std::vector make_wav(uint8_t channels, uint32_t sample_rate, siz static std::vector make_ogg_page(const std::vector& first_packet) { std::vector page; page.insert(page.end(), {'O', 'g', 'g', 'S'}); - page.push_back(0); // stream structure version - page.push_back(0x02); // header type: beginning of stream - page.insert(page.end(), 8, 0); // granule position - push_u32le(page, 0x1D0DECAF); // serial number - push_u32le(page, 0); // page sequence number - push_u32le(page, 0); // CRC (not validated by detection) - page.push_back(1); // segment count + page.push_back(0); // stream structure version + page.push_back(0x02); // header type: beginning of stream + page.insert(page.end(), 8, 0); // granule position + push_u32le(page, 0x1D0DECAF); // serial number + push_u32le(page, 0); // page sequence number + push_u32le(page, 0); // CRC (not validated by detection) + page.push_back(1); // segment count page.push_back(static_cast(first_packet.size())); // lacing value page.insert(page.end(), first_packet.begin(), first_packet.end()); return page; @@ -805,8 +807,8 @@ static bool test_detect_content_short_buffers() { } CHECK(detect_prefix(opus, 26) == AudioFileType::NONE); CHECK(detect_prefix(opus, 27) == AudioFileType::NONE); - CHECK(detect_prefix(opus, 28 + 4) == AudioFileType::NONE); // "Opus" only - CHECK(detect_prefix(opus, 28 + 8) == AudioFileType::OPUS); // full magic + CHECK(detect_prefix(opus, 28 + 4) == AudioFileType::NONE); // "Opus" only + CHECK(detect_prefix(opus, 28 + 8) == AudioFileType::OPUS); // full magic // Header claiming a 200-entry segment table but truncated inside it std::vector truncated(opus.begin(), opus.begin() + 27); @@ -1465,7 +1467,8 @@ static bool test_play_buffer_passthrough() { size_t frames; }; const Case cases[] = { - {2, 44100, 4096}, {1, 22050, 3333}, // odd frame count, mono + {2, 44100, 4096}, + {1, 22050, 3333}, // odd frame count, mono }; for (const Case& c : cases) { @@ -2805,18 +2808,25 @@ static bool count_worker_threads(size_t& readers, size_t& decoders) { /// @brief Waits for exactly this many reader and decoder threads to be running /// A new thread names itself once it runs, and a joined one can take a moment to leave the -/// OS's list, so this polls briefly. -/// @return true if the counts matched, or if thread names cannot be read here +/// OS's list, so this polls briefly. A match must then hold for a short settle window, so +/// that a thread started by mistake cannot slip past before it has named itself. +/// @return true if the counts matched and held, or if thread names cannot be read here static bool wait_worker_threads(size_t readers, size_t decoders) { + static constexpr uint64_t SETTLE_MS = 100; size_t r = 0; size_t d = 0; uint64_t deadline = now_ms() + 2000; + uint64_t matched_since = 0; do { // cppcheck-suppress knownConditionTrueFalse // false only off macOS and Linux if (!count_worker_threads(r, d)) { return true; } - if (r == readers && d == decoders) { + if (r != readers || d != decoders) { + matched_since = 0; + } else if (matched_since == 0) { + matched_since = now_ms(); + } else if (now_ms() - matched_since >= SETTLE_MS) { return true; } std::this_thread::sleep_for(std::chrono::milliseconds(5)); @@ -2976,6 +2986,8 @@ static bool test_prepare_twice_and_after_play() { std::vector payload_buf; std::vector wav = make_wav(2, 44100, 1024, &payload_buf, 0xF0F0F0F0); + std::vector long_payload; + std::vector long_wav = make_wav(2, 44100, 16384, &long_payload, 0x3C3C3C3C); { // Twice before any playback @@ -3010,15 +3022,20 @@ static bool test_prepare_twice_and_after_play() { CHECK(pump_to_completion(src, listener)); CHECK(wait_worker_threads(0, 1)); + // A long, throttled playback, so prepare() is certain to land in the middle of it listener.reset_capture(); - listener.max_consume = 256; // keep this playback going while prepare() runs + listener.max_consume = 256; listener.consume_delay_ms = 1; - CHECK(src.play_buffer(wav.data(), wav.size(), AudioFileType::WAV)); + CHECK(src.play_buffer(long_wav.data(), long_wav.size(), AudioFileType::WAV)); + CHECK(pump_until(src, [&]() { + return listener.saw_state(DecoderState::PLAYING) && listener.pcm_size() > 0; + })); + CHECK(listener.pcm_size() < long_payload.size()); CHECK(src.prepare()); CHECK(wait_worker_threads(1, 1)); CHECK(pump_to_completion(src, listener)); CHECK(!listener.saw_state(DecoderState::FAILED)); - CHECK(listener.pcm() == payload_buf); + CHECK(listener.pcm() == long_payload); listener.reset_capture(); listener.max_consume = SIZE_MAX; @@ -3036,6 +3053,50 @@ static bool test_prepare_twice_and_after_play() { return true; } +static bool test_prepare_during_url_playback() { + // prepare() mid-stream must leave the held ring buffer alone: it never resets or + // frees, so a URL playback with unread data in a persistent ring buffer has to come + // out bit-exact. The listener is throttled so the ring buffer is backed up with data + // when prepare() runs, and the playback is checked to be unfinished at that point. + DecoderConfig config; + config.persistent_threads = true; + config.persistent_ring_buffer = true; + config.ring_buffer_size = 16 * 1024; + + std::vector payload; + TestHttpServer::Response resp; + resp.content_type = "audio/wav"; + resp.body = make_wav(2, 44100, 32768, &payload, 0x7E7E7E7E); + TestHttpServer server; + CHECK(server.start(resp)); + + ThreadIdListener listener; + listener.max_consume = 256; + listener.consume_delay_ms = 1; + DecoderSource src(config); + src.set_listener(&listener); + + for (int round = 0; round < 2; ++round) { + // The first round's prepare() finds both threads already created by play_url() + listener.reset_capture(); + CHECK(src.play_url(server.url("/stream"))); + CHECK(pump_until(src, [&]() { + return listener.saw_state(DecoderState::PLAYING) && listener.pcm_size() > 0; + })); + CHECK(listener.pcm_size() < payload.size()); + CHECK(src.prepare()); + CHECK(src.prepare()); + CHECK(pump_to_completion(src, listener)); + CHECK(!listener.saw_state(DecoderState::FAILED)); + CHECK(listener.pcm() == payload); + CHECK(wait_worker_threads(1, 1)); + } + CHECK_EQ(listener.distinct_decoder_threads(), 1u); + + server.stop(); + return true; +} + static bool test_prepare_then_destroy() { // Destroying right after prepare(), with no playback ever handed to the workers, must // shut both down cleanly, including while the reader may still be setting itself up. @@ -3162,11 +3223,34 @@ static const TestCase TESTS[] = { {"prepare_allocates_only_what_config_keeps", test_prepare_allocates_only_what_config_keeps}, {"prepare_reuses_threads_and_ring_buffer", test_prepare_reuses_threads_and_ring_buffer}, {"prepare_twice_and_after_play", test_prepare_twice_and_after_play}, + {"prepare_during_url_playback", test_prepare_during_url_playback}, {"prepare_then_destroy", test_prepare_then_destroy}, {"prepare_then_stop", test_prepare_then_stop}, }; +/// @brief Compares the TESTS table with the names CMake registers with ctest +/// @return Process exit code: 0 if both list exactly the same tests +static int check_registered(int count, char* names[]) { + std::set registered(names, names + count); + int problems = 0; + for (const TestCase& t : TESTS) { + if (registered.erase(t.name) == 0) { + std::printf("%s is not in DECODER_TESTS in tests/CMakeLists.txt\n", t.name); + ++problems; + } + } + for (const std::string& name : registered) { + std::printf("%s is registered with ctest but not in the TESTS table\n", name.c_str()); + ++problems; + } + return problems == 0 ? 0 : 1; +} + int main(int argc, char* argv[]) { + if (argc > 1 && std::strcmp(argv[1], "--check-registered") == 0) { + return check_registered(argc - 2, argv + 2); + } + const char* filter = (argc > 1) ? argv[1] : nullptr; set_log_level(LOG_LEVEL_ERROR); // keep expected-failure noise out of test output From ca14fa25dccc5f380c6a3f8dc01ecf253b658da9 Mon Sep 17 00:00:00 2001 From: Kevin Ahrendt Date: Fri, 4 Dec 2026 14:17:51 -0500 Subject: [PATCH 4/4] Declare the prepare test's listener and buffer before the DecoderSource 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. --- tests/test_micro_decoder.cpp | 9 ++++++--- 1 file changed, 6 insertions(+), 3 deletions(-) diff --git a/tests/test_micro_decoder.cpp b/tests/test_micro_decoder.cpp index 26e3031..15ca711 100644 --- a/tests/test_micro_decoder.cpp +++ b/tests/test_micro_decoder.cpp @@ -2856,6 +2856,12 @@ static bool check_prepare_allocations(bool persistent_threads, bool persistent_r config.persistent_ring_buffer = persistent_ring_buffer; config.ring_buffer_size = PREPARE_RING_BUFFER_SIZE; + // Declared before src so they outlive it: if a check fails mid-playback, the destructor + // stops the decoder while the listener and buffer it is using still exist + std::vector payload; + std::vector wav = make_wav(2, 44100, 1024, &payload); + CaptureListener listener; + size_t heap_before_construct = heap_bytes(); const size_t workers = persistent_threads ? 1 : 0; DecoderSource src(config); @@ -2885,9 +2891,6 @@ static bool check_prepare_allocations(bool persistent_threads, bool persistent_r #endif // Playback still works, and one-shot workers are still joined after it - std::vector payload; - std::vector wav = make_wav(2, 44100, 1024, &payload); - CaptureListener listener; src.set_listener(&listener); CHECK(src.play_buffer(wav.data(), wav.size(), AudioFileType::WAV)); CHECK(pump_to_completion(src, listener));