Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion CLAUDE.md
Original file line number Diff line number Diff line change
Expand Up @@ -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.

Expand Down
16 changes: 14 additions & 2 deletions docs/INTEGRATION.md
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand All @@ -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
Expand Down Expand Up @@ -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. |
Expand Down
22 changes: 22 additions & 0 deletions include/micro_decoder/decoder_source.h
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
5 changes: 3 additions & 2 deletions include/micro_decoder/types.h
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand All @@ -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};

// ========================================
Expand Down
87 changes: 74 additions & 13 deletions src/decoder_source.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -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
// ============================================================================
Expand Down Expand Up @@ -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()) {
Comment thread
kahrendt marked this conversation as resolved.
Resolved
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.
Expand Down Expand Up @@ -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);
Expand All @@ -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);
Expand Down Expand Up @@ -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<Impl*>(arg)->reader_thread_main();
return nullptr;
}
Expand Down Expand Up @@ -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<Impl*>(arg)->decoder_thread_main();
return nullptr;
}
Expand Down Expand Up @@ -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);
}
Expand Down
22 changes: 22 additions & 0 deletions src/platform/thread.h
Original file line number Diff line number Diff line change
Expand Up @@ -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)
Expand Down Expand Up @@ -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
10 changes: 10 additions & 0 deletions tests/CMakeLists.txt
Original file line number Diff line number Diff line change
Expand Up @@ -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)
Expand All @@ -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})
Loading
Loading