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
6 changes: 6 additions & 0 deletions .claude/skills/embedded-review/SKILL.md
Original file line number Diff line number Diff line change
Expand Up @@ -42,6 +42,12 @@ hunks: resource problems live in context.
loop tick) must not allocate. Look for `new`, `malloc`, `std::string` and
`std::vector` growth, and temporary `JsonDocument`s inside them. Persistent
reusable buffers are the established pattern.
- After `start()`, connection setup and message handling allocate through the
`platform_malloc` family only, never `operator new` (`std::string`,
`std::vector`, `make_shared`, a `std::function` with a wide capture): on
ESPHome `operator new` is internal-RAM-only and aborts. A new site belongs
in `docs/internals.md` "Memory" or is a finding (`docs/conventions.md`,
"Embedded resource discipline").
- Allocation goes through the `platform_malloc` family or
`PlatformBuffer`/`TransferBuffer` with a deliberate `MemoryLocation`:
internal RAM for latency-critical or DMA-adjacent data, SPIRAM-preferring
Expand Down
8 changes: 4 additions & 4 deletions CLAUDE.md
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@ Standalone C++ library implementing the Sendspin synchronized audio streaming pr

## Architecture

The library provides `SendspinClient` as the main public API. It handles the full protocol lifecycle: WebSocket connections, time synchronization, audio decoding/sync, and message routing. One library-owned protocol task owns every connection and does all protocol work; transports only receive (into the shared inbound ring or a connection's fallback buffer) and report closes; `loop()` only polls the network provider and drains the inbox (and, while stopped, frees parked outbound attempts). `docs/internals.md` has the threads, the cross-thread channels, the tick order and the cross-file invariants.
The library provides `SendspinClient` as the main public API. It handles the full protocol lifecycle: WebSocket connections, time synchronization, audio decoding/sync, and message routing. One library-owned protocol task owns every connection and does all protocol work; transports only receive (into the shared inbound ring or a connection's fallback buffer) and report closes; `loop()` only polls the network provider and drains the inbox (and, while stopped, frees parked outbound attempts). `docs/internals.md` has the threads, the cross-thread channels, the tick order, the allocation model and the cross-file invariants.

### Key classes

Expand Down Expand Up @@ -60,7 +60,7 @@ examples/source_client/ - Host example streaming the default PortAudio input
tests/ - Host unit tests (GoogleTest)
tests/esp_idf/ - Build-only ESP-IDF project checking the component's codec dependencies
tools/stack_usage/ - Script and indirect-call tables that derive the ESP task stack defaults from -fcallgraph-info
docs/ - integration-guide.md (consumer guide), internals.md (how the parts fit together: threads, cross-thread channels, tick order, cross-file invariants), playback-sync.md (clock sync and audio alignment), conventions.md (normative design standards)
docs/ - integration-guide.md (consumer guide), internals.md (how the parts fit together: threads, cross-thread channels, tick order, memory, cross-file invariants), playback-sync.md (clock sync and audio alignment), conventions.md (normative design standards)
.claude/skills/ - Review checklists applying the standards to a diff (docs-sync, embedded-review, house-patterns, test-standards)
```

Expand Down Expand Up @@ -94,7 +94,7 @@ Core source files in `src/` have no `#ifdef ESP_PLATFORM` guards; all platform d

- **ESP-IDF**: Used as an IDF component via `idf_component.yml`. Sources defined in `cmake/sources.cmake`.
- **Host (CMake)**: `cmake -B build && cmake --build build`. Uses ccache when installed (`SENDSPIN_USE_CCACHE`, default on when standalone). Fetches dependencies via FetchContent: ArduinoJson, noise-c, IXWebSocket, micro-flac for the player or source role, and micro-opus for the player or source role when `SENDSPIN_ENABLE_OPUS` is on.
- **Tests**: `cmake -B build-tests -DSENDSPIN_BUILD_TESTS=ON -DENABLE_SANITIZERS=ON -DBUILD_EXAMPLES=OFF .`, then `cmake --build build-tests --target sendspin_tests` and `ctest --test-dir build-tests --output-on-failure`.
- **Tests**: `cmake -B build-tests -DSENDSPIN_BUILD_TESTS=ON -DENABLE_SANITIZERS=ON -DBUILD_EXAMPLES=OFF .`, then `cmake --build build-tests --target sendspin_tests` and `ctest --test-dir build-tests --output-on-failure`. The target also builds `sendspin_alloc_tests`, which counts the library's `operator new` calls from accept to admission, for a `client/state` and for a time burst; `SENDSPIN_ALLOC_REPORT=1` prints them grouped by call site.
- **ThreadSanitizer tests**: `cmake -B build-tsan -DSENDSPIN_BUILD_TESTS=ON -DENABLE_TSAN=ON -DBUILD_EXAMPLES=OFF .`, then `cmake --build build-tsan --target sendspin_tests` and `TSAN_OPTIONS=halt_on_error=1 ctest --test-dir build-tsan --output-on-failure`. `ENABLE_TSAN` applies the thread sanitizer to every target, including the fetched dependencies, and cannot be combined with `ENABLE_SANITIZERS`.
- **Message trace**: `-DSENDSPIN_ENABLE_MESSAGE_TRACE=ON` compiles in `SendspinClientConfig::message_trace` and `tests/test_message_trace.cpp`; CI's test and TSan jobs build it on, the build and no-opus jobs off.
- **Stack budgets**: the ESP task stack defaults in `config.h` are static call-graph bounds from `tools/stack_usage/` (recipe and per-task figures in its README); re-derive them, and update the README table with them, after a change that deepens a task's call chain.
Expand All @@ -107,7 +107,7 @@ Core source files in `src/` have no `#ifdef ESP_PLATFORM` guards; all platform d
- C++20 (`gnu++20` on ESP, `cxx_std_20` on host)
- Namespace: `sendspin`
- Logging: Platform macros `SS_LOGE`, `SS_LOGW`, `SS_LOGI`, `SS_LOGD`, `SS_LOGV` (not raw `ESP_LOG*`)
- Memory: the `platform_malloc` family from `platform/memory.h`, never raw `heap_caps_malloc`/`malloc` in core code (variant semantics under Platform abstraction above)
- Memory: the `platform_malloc` family from `platform/memory.h`, never raw `heap_caps_malloc`/`malloc` in core code (variant semantics under Platform abstraction above); `operator new` only at construction, `add_*()` and `start()`, with bounded values held inline (`InlineText`, `InlineVector`, `EnumSet`). `docs/internals.md` "Memory" lists the exceptions
- Threading: `std::mutex`, `std::thread` (via pthreads on both platforms). ESP build also uses FreeRTOS primitives (`xRingbuffer`, queues, event groups) for performance via the platform abstraction layer. Connection state belongs to the protocol task; requests that act on a connection go through its command queue or, for latest-wins lifecycle requests, its request slot, and work bound for the main loop goes through the inbox. Every library lock is a leaf, so there is no lock order.
- Tests: host-only and white-box; a test file that reaches private members compiles with `-fno-access-control` (`tests/CMakeLists.txt` says what and why), never through a production seam
- Apache 2.0 license headers on all files
Expand Down
14 changes: 13 additions & 1 deletion docs/conventions.md
Original file line number Diff line number Diff line change
Expand Up @@ -171,6 +171,18 @@ checklists in `.claude/skills/` apply these standards to a diff.
Watch for aggressive inlining aggregating several frames into one.
- Hot paths (per audio chunk, per binary message, per visualizer frame) do not
allocate. Reuse persistent buffers; size them once with a stated derivation.
- `operator new` is for construction, `add_*()` and `start()`: on ESPHome it
draws only on internal RAM and aborts when it fails. After `start()`, a
connection's handshake and admission and the messages that follow allocate
only through the `platform_malloc` family, whose failure refuses or closes
the connection or drops the message. A value with a bound is held inline
(`InlineText`, `InlineVector`, `EnumSet`, `std::array`), and text from a peer
is bounded where it is parsed: read in place, refused past its cap, or cut to
its field's size. A public type keeps `std::string` and `std::vector`; where
its value has a bound, the library holds it inline and builds the public
type on the thread that hands it to the consumer. `docs/internals.md`
"Memory" lists the `operator new` allocations that remain after `start()`,
and `sendspin_alloc_tests` counts them on the paths it walks.
- Buffer and queue capacities are justified numbers. Derive related constants
from each other (`constexpr size_t X = Y / 4;`) so they cannot drift apart,
and do not grow a budget without recording why.
Expand Down Expand Up @@ -285,7 +297,7 @@ checklists in `.claude/skills/` apply these standards to a diff.

- `docs/internals.md` holds only facts that span files: the thread model,
cross-thread channels, the protocol task's tick and the `loop()` drain order,
and invariants that hold
the allocation model, and invariants that hold
across classes. Why a single function or member behaves as it does belongs
in a comment at that function or member, and protocol behavior is cited
from the spec rather than restated. Do not add test names or numeric
Expand Down
26 changes: 25 additions & 1 deletion docs/internals.md
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
# Sendspin-cpp Internals

This document maps how the library's parts work together: which threads exist, how state crosses between them, the order of one protocol-task tick and one `loop()` drain, and the invariants that span several files. It covers only facts that span files. Why a single function or member behaves as it does is documented at that function or member, and the protocol itself is specified by the Sendspin spec, cited here by section. The design rules new code must follow are in `docs/conventions.md`. How the library keeps audio in time with the server (clock sync and the sync task's alignment) is in `docs/playback-sync.md`.
This document maps how the library's parts work together: which threads exist, how state crosses between them, the order of one protocol-task tick and one `loop()` drain, where memory comes from, and the invariants that span several files. It covers only facts that span files. Why a single function or member behaves as it does is documented at that function or member, and the protocol itself is specified by the Sendspin spec, cited here by section. The design rules new code must follow are in `docs/conventions.md`. How the library keeps audio in time with the server (clock sync and the sync task's alignment) is in `docs/playback-sync.md`.

## Code Organization

Expand Down Expand Up @@ -453,3 +453,27 @@ On ESP, a `SendspinServerConnection`'s lifetime belongs to its httpd session rat
4. On close, httpd calls `close_fn`, which marks the connection's inbound gate closed and wakes the protocol task; the task drops its observer once the messages the session delivered before closing are processed. httpd calls `free_fn` once no worker is queued for the session.

On host, IXWebSocket callbacks hold a `weak_ptr` to the connection the manager accepted and lock it per message, so this scheme is not needed. A connection the client refuses at delivery is closed and released by the open handler once the delivery has returned, so the refusal does not destroy it inside the delivery either; holding it until the socket's Close would only add a reference cycle through the WebSocket's own callback, since its destructor is trivial and the IX server owns the WebSocket.

## Memory

The library allocates from heaps that fail differently. `operator new`, behind every `std::string`, `std::vector` and `std::make_shared` and any `std::function` whose capture outgrows its small buffer, draws on ESPHome only on internal RAM and aborts when it fails. The `platform_malloc` family (`src/platform/memory.h`, behind `PlatformBuffer` and the JSON arena's overflow) places each block by its `MemoryLocation`, and noise-c allocates its handshake, cipher and hash states with `calloc`; both report a failure, which the caller turns into a refused or closed connection or a dropped message. The exceptions are drawing random bytes (`platform_random_bytes()`) and hashing a PSK into its `psk_id` (`psk_id_for()` on a `std::array`), which abort when noise-c cannot allocate the random or hash state. Construction, `add_*()` and `start()` use any of them. After `start()`, the per-connection and per-message buffers come from the `platform_malloc` family: the JSON arena's overflow, the handshake's prologue, msg1 and msg2 buffers, the fallback buffer, the Noise transport's reassembly and send buffers, and on ESP a send that does not fit the `FixedBlockPool`. The host transport, whose IXWebSocket API copies each frame into a `std::string`, and the host-only message trace sit outside this model: ESP replaces the first with esp_http_server and esp_websocket_client and builds without the second.

Bounded values stay inline: the ids and names a connection holds (`IdText`, `ServerName`), activity and player command sets (`EnumSet`), role sets (`ActiveRoles` and role masks), the protocol task's slot tables (`InlineVector`), and each connection's `NoiseSession`, which owns the noise-c handshake and cipher states, and `NoiseHandshake`. A getter that returns `std::string`, such as the server's id and name, builds it from the inline value on the caller's thread.

`operator new` runs after `start()` at these places:

| What | When |
|------|------|
| The connection object, one block that holds its Noise session, handshake and pairing session | Each ESP accept, on the httpd task, with the `shared_ptr` the httpd session slot holds; each `connect_to()`, its URL copied into the request slot on the caller's thread and into the transport on the protocol task. A host accept's is the IXWebSocket transport's |
| Message fields held on the heap: track metadata, controller `supported_commands`, `group/update`'s `group_id` and `group_name`, `stream/start`'s `codec_header`, artwork channels and visualizer types, and the `stream/end` and `stream/clear` role lists | Each message that carries them, parsed on the protocol task. `group/update`'s fields are copied again into the inbox slot's merged value on the protocol task and into the client's group state on the main loop |
| The artwork channels and visualizer types of `client/state` | Each `client/state` with the artwork or visualizer role: built on the main loop, copied for each connection on the protocol task |
| The CPace round state, each built pairing message's base64 fields, the pairing notes for the main loop, a new pairing record | Each pairing exchange, on the protocol task |
| The record store's list of changed slots; its slot and order blob writes | A pairing or a `server/unpair`, on the protocol task; the flush that follows a pairing, a `server/unpair` or a playback handoff to another paired server, on the main loop |
| The decode buffer's `TransferBuffer`; a FLAC decoder | The first codec header after `start()`, and each FLAC codec header, on the sync task |
| The source's codec header | Each source stream start, on the protocol task |
| The visualizer's spectrum bins | The first spectrum frame after `start()`, and one with more bins, on the drain thread |
| The player's stream events held for the sync task's idle | Events beyond the list's kept capacity, on the main loop |
| The ESP server's pending upgrades (`pending_`) and the list a reap collects them in | An upgrade waiting for delivery, on the httpd task; a reap at its deadline, on the protocol task |
| `closing_` | The shutdown pass, on the protocol task |

The `std::function`s built after `start()` allocate nothing because each capture is one pointer, which fits both standard libraries' small buffer: the Noise transport's frame sinks, set as each connection is constructed; the frame write hook a time send builds, which ESP copies into each send; and the handshake's send function, built for each handshake frame. A change to one of these captures is checked against that buffer, since a callable that does not fit it allocates on every copy.
Loading