Standalone C++ library implementing the Sendspin synchronized audio streaming protocol. Builds on both ESP-IDF (ESP32) and host platforms (macOS/Linux). Designed to be consumed by ESPHome but has no ESPHome dependencies.
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.
SendspinClient(client.h): main orchestration class; owns the protocol task, the connection manager, the inbound ring and the message routing. Its protocol-task half (the tick, the command handler, the JSON and binary dispatch) is inclient_dispatch.cppProtocolTask(protocol_task.h): theSsProtothread, its bounded command queue, the latest client/state slot and the never-refused lifecycle-request slot; ticks throughSendspinClient::protocol_tick()to its next deadlineConnectionManager(connection_manager.h): the admitted array with role ownership, the nursery, the reaping list, admission and arbitration, time bursts, watchdogs and the published clocks and server information; pairing state machines inconnection_manager_pairing.cppInboundRing/InboundItemList/InboundConsumer/InboundGate(inbound_ring.h): the shared ring every admitted transport receives into (overSharedRingBuffer), the intrusive per-role item lists that hand audio, visualizer frames and artwork image parts to their consumer threads in place, and the per-connection transport/protocol-task hand-offOutboundRing(outbound_ring.h): a ring one producer thread (the source task) writes outbound binary messages into; the protocol task encrypts each in place and lends its item to the transport, which returns it once the frame is written. The source's capture ring reuses the classPlayerRole(player_role.h): audio streaming role, ownsSyncTask, writes decoded audio viaon_audio_outputcallback, each write carrying its formatControllerRole(controller_role.h): sends playback commands to the serverMetadataRole(metadata_role.h): receives track metadata and progressArtworkRole(artwork_role.h): receives album artwork images; its decode thread takes each image's announce, parts and discard markers from its item list, copies each part into one buffer per channel and returns its item at once, and parks a complete image there while the channel'sframe_done()gate is closedVisualizerRole(visualizer_role.h): receives spectrum/beat visualization dataColorRole(color_role.h): receives audio-derived RGB color palette from the serverSourceRole(source_role.h): streams captured audio to the server (source@v1); takes PCM throughwrite_audio()from the consumer's capture thread, and runs the input stream's lifecycle and chunk sends on the protocol taskSourceTask(source_task.h): assembles the capture ring's writes into timestamped chunks, encoded through theSourceEncoderseam (source_encoder.h: the PCM passthrough,FlacSourceEncoderinsource_encoder_flac.h, orOpusSourceEncoderinsource_encoder_opus.hwhen built withSENDSPIN_ENABLE_OPUS) into the source's outbound ring for the protocol task to sendSyncTask(sync_task.h): decodes encoded audio from its item list in place, synchronizes to server timestamps, writes PCM via audio write callbackSendspinConnection(connection.h): abstract WebSocket connection baseSendspinServerConnection/SendspinClientConnection: platform-specific WebSocket transports (ESP usesesp_websocket_client/esp_http_server, host uses IXWebSocket)NoiseHandshake(noise_handshake.h): drives the Noise KKpsk2 handshake frames and resolves the PSK throughRecordStoreNoiseSession(noise_session.h): noise-c wrapper holding the KKpsk2 handshake and transport cipher statesNoiseTransport(noise_transport.h): per-connection encrypted framing, owns fragmentation and reassembly around the sessionRecordStore(record_store.h): pairing records and the Pairing PSK (configured, stored, or generated), seeded from the client config and the persistence providerInbox/InboxSlot/GenerationSlot(inbox.h): single-mutex mailbox for all main-loop-bound cross-thread state - atomic topic bitmask polled lock-free byloop(), plus a fixed event ring for ordered lifecycle eventsScheduledStateSlot(scheduled_state_slot.h): the metadata and color roles' generation-stamped slot, which also keeps the state waiting for its server-clock timestamp, anddrain_scheduled_state(), their shared peek / decide-with-no-lock / commit drainRoleTeardown/TeardownTracker(teardown_tracker.h): every role's teardown generation and the main-loop half of a role's teardownMessageTracer(message_trace.h): one connection's handle on the opt-in plaintext message trace (SendspinClientConfig::message_trace), built only withSENDSPIN_ENABLE_MESSAGE_TRACESendspinTimeFilter(time_filter.h): 2D Kalman filter for NTP-style time syncSendspinTimeBurst(time_burst.h): burst-based time message coordinator, one per connectionSendspinDecoder(decoder.h): FLAC/PCM decoder wrapper, plus Opus when built withSENDSPIN_ENABLE_OPUS
Roles are added to the client at runtime via add_player(), add_metadata(), etc. Each role receives a SendspinClient* at construction time and uses it to access shared services (time sync, state publishing, message sending). The consumer provides behavior by implementing listener interfaces (PlayerRoleListener, MetadataRoleListener, etc.) and setting them via set_listener(). Required callbacks are pure virtual; optional callbacks have default no-op implementations. The client dispatches messages to roles via null-pointer checks on role pointers.
Roles can be disabled at compile time via SENDSPIN_ENABLE_* cmake options (host build) or Kconfig entries (ESP-IDF build). When a role is disabled, its source files are not compiled and its add_*() declaration, accessor, and unique_ptr member are removed from client.h. Role #ifdef guards live in exactly two places in the library: cmake/sources.cmake (source lists) and include/sendspin/client.h, src/client.cpp and src/client_dispatch.cpp (dispatch points); the codec gate SENDSPIN_ENABLE_OPUS (cmake option / Kconfig entry, default on) lives only in src/decoder.h, src/decoder.cpp, src/player_role.cpp, src/source_role.cpp, and src/source_task.cpp, plus the SENDSPIN_SOURCE_OPUS_SOURCES list (src/source_encoder_opus.cpp) in cmake/sources.cmake. The host-only message trace gate SENDSPIN_ENABLE_MESSAGE_TRACE (cmake option, default off, no Kconfig entry) lives only in include/sendspin/config.h, src/connection.h, src/connection.cpp, src/connection_manager.cpp, src/noise_transport.h, src/noise_transport.cpp, and the SENDSPIN_MESSAGE_TRACE_SOURCES list (src/message_trace.cpp). Examples and tests guard their own role and opus usage like any consumer. micro-flac is only linked when the player or source role is enabled; micro-opus only with SENDSPIN_ENABLE_OPUS and the player or source role enabled.
The consuming platform (e.g., ESPHome) supplies the listener implementations plus SendspinNetworkProvider and the optional SendspinPersistenceProvider/SendspinClientListener providers; docs/integration-guide.md has the full wiring, including a minimal working example.
include/sendspin/ - Public API headers (client.h, config.h, types.h, persistence_keys.h, persistence_codec.h, *_role.h)
src/ - Cross-platform source files (.cpp) and private headers (.h)
src/crypto/ - Crypto primitives and Noise/pairing constants (CPace, pairing codes and tokens, PSK wrapping)
src/platform/ - Platform abstraction headers and host-only source files
src/esp/ - ESP-IDF networking implementations and headers
src/host/ - Host (IXWebSocket) networking implementations and headers
cmake/ - CMake modules (sources.cmake, host.cmake)
examples/common/ - Shared host-example helpers (PortAudio sink, file-backed persistence provider)
examples/basic_client/ - Standalone host example with PortAudio audio output
examples/tui_client/ - Terminal UI host example with PortAudio audio output
examples/source_client/ - Host example streaming the default PortAudio input (source role)
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, 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)
- Public (
include/sendspin/):client.h,config.h,types.h,persistence_keys.h,persistence_codec.h, and role headers (player_role.h,controller_role.h,metadata_role.h,artwork_role.h,visualizer_role.h,color_role.h,source_role.h). These are the consumer-facing API.config.hcontains all configuration structs (SendspinClientConfigand role configs). Each role header defines its own protocol types (enums, structs, conversion functions).types.hcontains shared types used across the client and roles.persistence_keys.hholds the fixed storage keys and blob sizesSendspinPersistenceProvideris called with (client.hincludes it).persistence_codec.hprovides the binary, fixed-size storage codec the library itself uses to turn the pairing structs into the blobs it hands toSendspinPersistenceProvider::write_blob(); it is public so a custom provider or test can inspect/seed that same content. - Private (
src/): All internal headers (decoder, sync_task, time_filter, ring buffers, protocol_messages, etc.). Not exposed to consumers.protocol_messages.hcontains message envelope structs, internal protocol enums, and protocol function declarations. - Platform-specific (
src/esp/,src/host/): Networking headers with the same names (client_connection.h,server_connection.h,ws_server.h) but different implementations per platform.
Headers in src/platform/ use #ifdef ESP_PLATFORM to provide unified APIs across platforms:
logging.h:SS_LOGE/SS_LOGW/SS_LOGI/SS_LOGD/SS_LOGVmacros (ESP:esp_log.h, host:printf-based)memory.h:platform_malloc/platform_realloc/platform_malloc_internal/platform_realloc_internal/platform_free(ESP: SPIRAM-preferring or internal-RAM-preferringheap_caps_malloc_prefer, host: standardmalloc).PlatformBufferaccepts aMemoryLocation(defined ininclude/sendspin/types.h) to select the preference.thread.h: threading utilitiestime.h: time utilitiesbase64.h: base64 encoding/decodingcompiler.h: compiler hints and platform-specific macroscrypto.h: SHA-256/SHA-512, HMAC-SHA-512, X25519, one-shot ChaChaPoly AEAD, CSPRNG, constant-time compare and secure zerosecure_zero.h: secret erasure that survives dead-store elimination, for callers that only wipe a bufferjson_arena.h: bounded internal-RAM bump-arena ArduinoJson allocator, wiping every block it frees, that backs every JSON document the protocol task parses or builds, plusParsedJsonMessage, the extract-then-release reader every parsed message goes throughnetwork_info.h: best-effort lookup of the local network interface MAC addresstypes.h: platform type abstractionsshared_ring_buffer.h: multi-producer ring buffer with acquire/complete writes, one ordered consumer, any-order returns and ring-order reclamation (ESP: FreeRTOS no-splitxRingbuffer, host: mutex/condition variable over the same layout)event_flags.h: event flag group (ESP: FreeRTOS event group, host: mutex/condition variable)shadow_slot.h: mutex-protected single-writer/single-reader slot between two threads (the sync task's playback-progress slot); state the main loop reads goes through the inbox (inbox.h) instead
Core source files in src/ have no #ifdef ESP_PLATFORM guards; all platform differences are isolated to the platform layer and the src/esp//src/host/ directories.
- ESP-IDF: Used as an IDF component via
idf_component.yml. Sources defined incmake/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 whenSENDSPIN_ENABLE_OPUSis on. - Tests:
cmake -B build-tests -DSENDSPIN_BUILD_TESTS=ON -DENABLE_SANITIZERS=ON -DBUILD_EXAMPLES=OFF ., thencmake --build build-tests --target sendspin_testsandctest --test-dir build-tests --output-on-failure. The target also buildssendspin_alloc_tests, which counts the library'soperator newcalls from accept to admission, fromconnect_to()to admission, for aclient/state, for a time burst, for a controllerserver/state, forgroup/update, for metadataserver/state(a first state, a second, a scheduled one and one without text), for thestream/*messages, for the sync task's first FLAC codec header, for a FLACstream/startthe player takes, for one that changes the running stream's sample rate, for astream/startsection the connection's roles do not take, for the first spectrum frame, and through the record flush that follows each of a playback handoff to another paired server, aserver/unpair, apairing_pskpairing and a dynamic pairing code pairing in each emission format;SENDSPIN_ALLOC_REPORT=1prints them grouped by call site. - ThreadSanitizer tests:
cmake -B build-tsan -DSENDSPIN_BUILD_TESTS=ON -DENABLE_TSAN=ON -DBUILD_EXAMPLES=OFF ., thencmake --build build-tsan --target sendspin_testsandTSAN_OPTIONS=halt_on_error=1 ctest --test-dir build-tsan --output-on-failure.ENABLE_TSANapplies the thread sanitizer to every target, including the fetched dependencies, and cannot be combined withENABLE_SANITIZERS. - Message trace:
-DSENDSPIN_ENABLE_MESSAGE_TRACE=ONcompiles inSendspinClientConfig::message_traceandtests/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.hare static call-graph bounds fromtools/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. - ESP dependencies: ArduinoJson, noise-c, esp_websocket_client, micro-flac, micro-opus (with
SENDSPIN_ENABLE_OPUS), esp_http_server, mbedtls, pthread, esp_ringbuf, esp_hw_support - Host dependencies: ArduinoJson, noise-c, micro-flac, micro-opus (with
SENDSPIN_ENABLE_OPUS), IXWebSocket, pthreads
- Design standards:
docs/conventions.mdis the normative reference (threading/Inbox rules, validation posture, platform abstraction, embedded resource discipline, public API shape, testing, documentation sync); the bullets below are a summary - C++20 (
gnu++20on ESP,cxx_std_20on host) - Namespace:
sendspin - Logging: Platform macros
SS_LOGE,SS_LOGW,SS_LOGI,SS_LOGD,SS_LOGV(not rawESP_LOG*) - Memory: the
platform_mallocfamily fromplatform/memory.h, never rawheap_caps_malloc/mallocin core code (variant semantics under Platform abstraction above);operator newonly at construction,add_*()andstart(), 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(the file names each member it reaches, and why, once: a reach several tests share at its top or on their fixture, any other on the test or helper that takes it), never through a production seam - Apache 2.0 license headers on all files
Configured in .pre-commit-config.yaml:
end-of-file-fixerandtrailing-whitespaceclang-format(v18) for C/C++ files undersrc/andinclude/markdownlint-fixfor markdown files