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..c5087aa 100644 --- a/docs/INTEGRATION.md +++ b/docs/INTEGRATION.md @@ -158,6 +158,8 @@ Threads follow the same pattern. By default each `play_*()` call creates the thr config.persistent_threads = true; ``` +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: ```cpp @@ -180,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 @@ -386,8 +398,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..cfba961 100644 --- a/include/micro_decoder/decoder_source.h +++ b/include/micro_decoder/decoder_source.h @@ -83,6 +83,28 @@ 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. 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 /// @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..b35e9ca 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,43 @@ 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() { + 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)) { + MD_LOGW(TAG, "Failed to allocate the ring buffer; will retry on playback"); + ok = false; + } + } + if (this->config.persistent_threads) { + // 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 +281,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 +318,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 +372,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 +468,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 +636,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..65d10e5 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. 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) + (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/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 a3ce417..15ca711 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" @@ -45,12 +46,34 @@ #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 +// 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 #include #include @@ -2718,6 +2741,441 @@ 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. 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) { + 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)); + } 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; + + // 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); + // 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 + 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); + std::vector long_payload; + std::vector long_wav = make_wav(2, 44100, 16384, &long_payload, 0x3C3C3C3C); + + { + // 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)); + + // A long, throttled playback, so prepare() is certain to land in the middle of it + listener.reset_capture(); + listener.max_consume = 256; + listener.consume_delay_ms = 1; + 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() == long_payload); + + 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_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. + // 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,9 +3223,37 @@ 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_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