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 @@ -10,7 +10,7 @@ The library provides `SendspinClient` as the main public API. It handles the ful

- `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 in `client_dispatch.cpp`
- `ProtocolTask` (`protocol_task.h`): the `SsProto` thread, its bounded command queue, the latest client/state slot and the never-refused lifecycle-request slot; ticks through `SendspinClient::protocol_tick()` to its next deadline
- `ConnectionManager` (`connection_manager.h`): the admitted array with role ownership, the nursery, the reaping list, admission and arbitration, time bursts, watchdogs and the published time filter and server information; pairing state machines in `connection_manager_pairing.cpp`
- `ConnectionManager` (`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 in `connection_manager_pairing.cpp`
- `InboundRing` / `InboundItemList` / `InboundConsumer` / `InboundGate` (`inbound_ring.h`): the shared ring every admitted transport receives into (over `SharedRingBuffer`), 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-off
- `OutboundRing` (`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 class
- `PlayerRole` (`player_role.h`): audio streaming role, owns `SyncTask`, writes decoded audio via `on_audio_write` callback
Expand Down
9 changes: 4 additions & 5 deletions docs/conventions.md
Original file line number Diff line number Diff line change
Expand Up @@ -52,9 +52,9 @@ checklists in `.claude/skills/` apply these standards to a diff.
- State published from one writer thread to one reader thread uses a
`ShadowSlot` (`src/platform/shadow_slot.h`), whichever side (if either) the
main loop is on. State the main loop *reads* goes through the Inbox instead.
The values read by several threads without being consumed, the primary
admitted connection's time filter and server information, sit in
`ConnectionManager`'s own slot behind a leaf mutex (`time_filter()`,
The values read by several threads without being consumed, the admitted
connections' clocks and the primary's server information, sit in
`ConnectionManager`'s own slot behind a leaf mutex (`clock()`,
`server_information()`), written by the protocol task; a flag read the same
way is a plain atomic.
- Event producers push through `push_event_or_log()` rather than hand-rolling
Expand Down Expand Up @@ -118,8 +118,7 @@ checklists in `.claude/skills/` apply these standards to a diff.
state, never across a call that takes another library lock, a send, a
listener or the persistence provider, so the library has no lock order to
cite. The leaves are `ConnectionManager::published_mutex_`,
`RecordStore::mutex_`, the Inbox mutex, each
`SendspinTimeFilter`'s `state_mutex_`, the inbound ring's, each outbound
`RecordStore::mutex_`, the Inbox mutex, the inbound ring's, each outbound
ring's, item lists' and protocol task command queue's own locks, the artwork
role's slot mutex, `ShadowSlot`'s and the ESP server's pending-upgrade mutex. A
change that would take a second library lock under one of them is a design
Expand Down
13 changes: 6 additions & 7 deletions docs/internals.md
Original file line number Diff line number Diff line change
Expand Up @@ -50,15 +50,14 @@ The primitives other than the Inbox and the inbound and outbound rings live in `
| Artwork `SlotGate`s (`DrainTask::slot_gates`, under `slot_mutex`) | Artwork decode thread (arms a gate, parks a complete image); main loop (presents, acks, drops a park at a stream end) | Each other |
| `ShadowSlot` (sync-task playback progress) | The consumer's audio thread (`notify_audio_played()`) | Sync task |
| `Inbox` (`src/inbox.h`, see [Inbox](#inbox)) | Protocol task, sync task, artwork decode thread | Main loop |
| `ConnectionManager` published primary slot (time filter and server information) | Protocol task (`refresh_published_state()`) | Any thread (`time_filter()`, `server_information()`) |
| Each connection's `SendspinTimeFilter` | Protocol task (its burst's measurements) | Sync task and visualizer drain thread, converting timestamps |
| `ConnectionManager` published state (each admitted slot's clock, the primary's server information) | Protocol task (`refresh_published_state()`) | Any thread (`clock()`, `server_information()`) |
| `RecordStore` | Protocol task (resolves and changes records) | Main loop (writes them to the provider) |

Plain atomics carry the rest: the `connected_` flag on `ConnectionManager`; the admission flag `accepting_` on `ProtocolTask`, written on the main loop under the queue lock; the unpaired-access setting, the lifecycle state, the network provider's last answer (`network_ready_`, written by the main loop's poll and read by the protocol task before it starts the WebSocket server) and the high-performance grant count (`high_performance_granted_`, see [One Main Loop Drain](#one-main-loop-drain)) on `SendspinClient`; and each role's teardown generation (`cleanup_generation`), written by the protocol task and read by the main loop and the role's thread. The role- and connection-local atomics (a connection's last-arrival stamp, upgrade flag and time-frame write time; artwork's `stream_active` and slot epochs, the visualizer's `spectrum_bin_count`, `tracks_downbeats` and `boundary_sequence`, the player's output delay, the controller's supported commands, the source's stream gate and codec, the source task's overflow generation) each state their writer and reader at their declaration.

### Locks

Every library lock is a leaf: it is held only to copy or update its own state, never across a call that takes another library lock, a send, a listener or the persistence provider, so no two library locks are ever held at once and there is no lock order. The locks are the Inbox's `mutex_`; the inbound ring's own and each outbound ring's, the source's capture ring included (`SharedRingBuffer::mtx_` on host, the FreeRTOS ring's internal lock on ESP); each `InboundItemList::mutex_`; `ProtocolTask::command_mutex_` (the command queue, the state slot and the request slot); `ConnectionManager::published_mutex_` (which also serialises the role threads' `time_filter()` reads behind `server_information()` copies); each `SendspinTimeFilter::state_mutex_`; `RecordStore::mutex_`; the artwork role's `DrainTask::slot_mutex` (its ack gates, between the decode thread and the main loop); each `ShadowSlot::mutex_`; the ESP server's `SendspinWsServer::pending_mutex_`; and, on host, the mutex inside `EventFlags`. Connection state has no lock at all: only the protocol task touches it, except the transport's own atomics, which state their writer and reader at their declaration.
Every library lock is a leaf: it is held only to copy or update its own state, never across a call that takes another library lock, a send, a listener or the persistence provider, so no two library locks are ever held at once and there is no lock order. The locks are the Inbox's `mutex_`; the inbound ring's own and each outbound ring's, the source's capture ring included (`SharedRingBuffer::mtx_` on host, the FreeRTOS ring's internal lock on ESP); each `InboundItemList::mutex_`; `ProtocolTask::command_mutex_` (the command queue, the state slot and the request slot); `ConnectionManager::published_mutex_` (which also serialises the role threads' `clock()` reads behind `server_information()` copies); `RecordStore::mutex_`; the artwork role's `DrainTask::slot_mutex` (its ack gates, between the decode thread and the main loop); each `ShadowSlot::mutex_`; the ESP server's `SendspinWsServer::pending_mutex_`; and, on host, the mutex inside `EventFlags`. Connection state has no lock at all: only the protocol task touches it, except the transport's own atomics, which state their writer and reader at their declaration.

### The Inbound Ring

Expand Down Expand Up @@ -130,9 +129,9 @@ Every role state slot is a `GenerationSlot<T>`: each payload carries the stamp i
OUTBOUND_RING_ITEM_COUNT chunks from its outbound ring, each sent or returned unsent
10. Losses from the sends of steps 7 to 9: a connection a failed send detached is dropped, as in
step 6, before anything is published
11. ConnectionManager::refresh_published_state(): the published primary slot (time filter and
server information); then publish_connected(), the connected flag other threads read,
raised only here, after every handler of the tick, so is_connected() never reads true
11. ConnectionManager::refresh_published_state(): the published state (each admitted slot's
clock, the primary's server information); then publish_connected(), the connected flag
other threads read, raised only here, after every handler of the tick, so is_connected() never reads true
before the tick's whole effect (the published slots and the events it queued for the
drain); a loss lowers it at once
```
Expand Down Expand Up @@ -400,7 +399,7 @@ A later `server/activate` can remove roles. Each removed role runs the same `cle

### Time Filter Slot

Role threads convert server timestamps through `SendspinClient::is_time_synced()` and `get_client_time()`: the sync task per chunk, the visualizer drain thread per frame. The source's chunks are converted the other way on the protocol task itself, through the stream connection's own filter, so they read no slot. Both resolve the primary admitted connection's `SendspinTimeFilter` through `ConnectionManager::time_filter()`, which reads the `PublishedPrimary` slot (`published_`, under the leaf `published_mutex_`) and never waits on the protocol task. `refresh_published_state()` writes that one slot, holding both the filter and the server information, whenever the primary connection changes, so it always names the primary connection's filter; a role thread holding the filter never holds the connection, whose destructor can join a transport thread.
Each connection's `SendspinTimeFilter` is a member of the connection, used on the protocol task only: its burst feeds it, and the source's chunks are converted the other way there, through the stream connection's own filter. Role threads convert server timestamps through `SendspinClient::is_time_synced()` and `get_client_time()`: the sync task per chunk, the visualizer drain thread per frame. Both read the primary admitted connection's clock through `ConnectionManager::clock()`: a `TimeTransform`, the filter's offset and drift as of its latest measurement, copied out of `published_` under the leaf `published_mutex_`, so a reader never waits on the protocol task and shares nothing with the connection, whose destructor can join a transport thread. `refresh_published_state()` (tick step 11) takes each admitted slot's transform and writes them, with the primary's slot, whenever one changed: a measurement, a new connection in the slot or a new primary.

Each getter reads the slot once, so a caller that checks `is_time_synced()` and then calls `get_client_time()` can see two different connections across a server handoff. A drop or handoff commands the stream to end before it changes the slot, so the sync task leaves the stream before transferring such a chunk; the shutdown pass empties the slot before the role threads stop, and the 0 an empty slot returns reads as late.

Expand Down
4 changes: 2 additions & 2 deletions docs/playback-sync.md
Original file line number Diff line number Diff line change
Expand Up @@ -4,13 +4,13 @@ This document explains how the library keeps audio in time with the server: esti

## Clock Synchronization

Each connection owns one `SendspinTimeFilter` (`src/time_filter.h`), created once when the connection is set up and never replaced, and one `SendspinTimeBurst`. Only that connection's own measurements feed its filter: the protocol task hands a `server/time` reply to the burst of the connection it arrived on, and only when it answers that connection's `client/time` in flight. The role threads convert through the primary admitted connection's filter (`docs/internals.md`, "Time Filter Slot").
Each connection owns one `SendspinTimeFilter` (`src/time_filter.h`), created once when the connection is set up and never replaced, and one `SendspinTimeBurst`. Only that connection's own measurements feed its filter: the protocol task hands a `server/time` reply to the burst of the connection it arrived on, and only when it answers that connection's `client/time` in flight. The role threads convert through a copy of the primary admitted connection's filter transform (`docs/internals.md`, "Time Filter Slot").

`SendspinTimeBurst` (`src/time_burst.h`) collects measurements in NTP-style bursts: `time_burst_size` `client/time` exchanges whose lowest-round-trip measurement goes to the filter, then a pause of `time_burst_interval_ms` until the next burst (both in `SendspinClientConfig`). The protocol task runs each admitted connection's burst while that connection is operational, and high-performance networking is held for its duration so the round trips are not inflated by power saving: the burst sends its first `client/time` only once the main loop has delivered the request to the listener (`docs/internals.md`, "One Main Loop Drain").

Each `client/time` round trip is timed from the socket write, not from the time the message carries: `SendspinConnection::send_time_message()` hands `NoiseTransport::send_staged_json()` a hook that the transport runs immediately before writing the message's frame, and the echoed `client_transmitted` only identifies the frame a `server/time` answers (`SendspinConnection::claim_time_frame()`). Recording the write time before the write, never after it, keeps every scheduling delay on the side that lengthens the measured round trip, which `max_error` reports and the burst's lowest-round-trip selection discards.

The filter is a two-state `[offset, drift]` Kalman filter, tuned by `SendspinTimeFilter::Config`. Drift is estimated from the second measurement on, but applied to time conversions only once it is statistically significant (`drift_significance_threshold`). Once `min_samples` measurements have accumulated, a residual larger than `adaptive_cutoff` times the measurement's round-trip error inflates the covariances, so the filter recovers quickly from a step change in the server's clock. Its `state_mutex_` lets the sync task and the visualizer drain thread convert timestamps while the protocol task updates it.
The filter is a two-state `[offset, drift]` Kalman filter, tuned by `SendspinTimeFilter::Config`. Drift is estimated from the second measurement on, but applied to time conversions only once it is statistically significant (`drift_significance_threshold`). Once `min_samples` measurements have accumulated, a residual larger than `adaptive_cutoff` times the measurement's round-trip error inflates the covariances, so the filter recovers quickly from a step change in the server's clock. The protocol task alone updates and reads it; the sync task and the visualizer drain thread convert timestamps through the copy of its transform it publishes.

The filter's first measurement gates playback: the sync task decodes no audio until the clock is synced. While the player role is active, it also gates the client's `client/state` reporting `available: true` (messaging.md "client/state").

Expand Down
12 changes: 6 additions & 6 deletions src/client.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -1194,15 +1194,15 @@ bool SendspinClient::is_connected() const {
}

bool SendspinClient::is_time_synced() const {
// See ConnectionManager::time_filter().
auto filter = this->connection_manager_->time_filter();
return filter != nullptr && filter->has_update();
// See ConnectionManager::clock().
const std::optional<TimeTransform> clock = this->connection_manager_->clock();
return clock.has_value() && clock->synced;
}

int64_t SendspinClient::get_client_time(int64_t server_time) const {
// See ConnectionManager::time_filter().
auto filter = this->connection_manager_->time_filter();
return filter != nullptr ? filter->compute_client_time(server_time) : 0;
// See ConnectionManager::clock().
const std::optional<TimeTransform> clock = this->connection_manager_->clock();
return clock.has_value() ? clock->compute_client_time(server_time) : 0;
}

std::optional<ServerInformationObject> SendspinClient::get_server_information() const {
Expand Down
8 changes: 0 additions & 8 deletions src/connection.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -74,14 +74,6 @@ SsErr SendspinConnection::send_lent_frame(OutboundRing& ring, void* item, size_t
return err;
}

// ============================================================================
// Time filter
// ============================================================================

void SendspinConnection::init_time_filter() {
this->time_filter_ = std::make_shared<SendspinTimeFilter>(SendspinTimeFilter::Config{});
}

void SendspinConnection::wake_protocol_task() const {
if (this->inbound_task_ != nullptr) {
this->inbound_task_->wake();
Expand Down
32 changes: 10 additions & 22 deletions src/connection.h
Original file line number Diff line number Diff line change
Expand Up @@ -615,33 +615,21 @@ class SendspinConnection : public std::enable_shared_from_this<SendspinConnectio
this->pairing_finalized_ = false;
}

/// @brief Gets the time filter for this connection
/// @return Pointer to the time filter, or nullptr if not initialized.
SendspinTimeFilter* get_time_filter() {
return this->time_filter_.get();
/// @brief This connection's time filter. Protocol task only; other threads read its transform
/// through ConnectionManager::clock().
SendspinTimeFilter& time_filter() {
return this->time_filter_;
}

/// @brief Returns a shared reference to this connection's time filter, for ConnectionManager's
/// time filter slot (see ConnectionManager::time_filter())
/// @return The time filter, or nullptr if not initialized.
std::shared_ptr<SendspinTimeFilter> get_shared_time_filter() const {
const SendspinTimeFilter& time_filter() const {
return this->time_filter_;
}

/// @brief Returns true if the time filter has received at least one measurement
/// @return True if time synchronization has started, false otherwise.
bool is_time_synced() const {
if (this->time_filter_ == nullptr) {
return false;
}
return this->time_filter_->has_update();
return this->time_filter_.has_update();
}

/// @brief Initializes the time filter with Kalman parameters. Call once, before the connection
/// can enter a manager slot: ConnectionManager's time filter slot copies this filter at install
/// and never refreshes it.
void init_time_filter();

/// @brief This connection's time burst, which feeds its time filter. Protocol task only: the
/// burst sends its client/time frames there and is fed the server/time replies there.
SendspinTimeBurst& time_burst() {
Expand Down Expand Up @@ -1033,16 +1021,16 @@ class SendspinConnection : public std::enable_shared_from_this<SendspinConnectio
/// Sends this connection's client/time bursts and feeds its time filter. Protocol task only.
SendspinTimeBurst time_burst_{};

/// Time synchronization filter (Kalman-based), fed by time_burst_. Protocol task only; other
/// threads read its transform through ConnectionManager::clock().
SendspinTimeFilter time_filter_{};

/// Noise handshake driver, from init_noise_handshake() until the handshake completes or
/// aborts. Protocol task only.
std::optional<NoiseHandshake> noise_handshake_;

// Pointer fields

/// Time synchronization filter (Kalman-based). Shared so role threads can hold it without
/// holding this connection (ConnectionManager::time_filter()).
std::shared_ptr<SendspinTimeFilter> time_filter_;

/// Retained for re-handshake: pointer to the client identity supplied at
/// init_noise_handshake(). Lifetime is owned by SendspinClient (outlives connections).
const Identity* noise_identity_{nullptr};
Expand Down
Loading
Loading