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 docs/playback-sync.md
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,7 @@ Each connection owns one `SendspinTimeFilter` (`src/time_filter.h`), created onc

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. 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 is a two-state `[offset, drift]` Kalman filter, tuned by the constants in `src/time_filter.cpp`. Drift is estimated from the second measurement on, but applied to time conversions only once it is statistically significant (`DRIFT_SIGNIFICANCE_THRESHOLD_SQUARED`). Once `MIN_SAMPLES_FOR_FORGETTING` 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 or source role is active, it also gates the connection's `client/state` (messaging.md "Clock Synchronization", "stream/start").

Expand Down
14 changes: 5 additions & 9 deletions src/client_dispatch.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -114,7 +114,7 @@ namespace {
/// close_silently()). Protocol task only.
[[maybe_unused]] void close_on_malformed_binary(SendspinConnection* conn, SendspinRole role) {
SS_LOGW(TAG, "Malformed %s message; closing connection", to_cstr(role));
conn->close_silently(SendspinGoodbyeReason::UNAUTHORIZED);
conn->close_silently();
}

} // namespace
Expand Down Expand Up @@ -628,12 +628,8 @@ void SendspinClient::process_json_message(SendspinConnection& connection, const
if (!msg1_bytes.has_value() ||
!conn->handle_noise_rehandshake({msg1_bytes->data(), msg1_bytes->size()})) {
SS_LOGW(TAG, "noise/handshake re-handshake failed; closing connection");
// Do not leave a half-swapped session. UNAUTHORIZED is the closest available
// reason for a crypto failure, though close_silently() never transmits it
// (connection.md "Failure Handling": close without any application-level
// message). disconnect() can block on a transport join, which close_silently()
// avoids; see close_transport_now()'s doc comment in connection.h.
conn->close_silently(SendspinGoodbyeReason::UNAUTHORIZED);
// Do not leave a half-swapped session (connection.md "Failure Handling").
conn->close_silently();
}
break;
}
Expand Down Expand Up @@ -706,7 +702,7 @@ void SendspinClient::process_json_message(SendspinConnection& connection, const
// error the client MUST close the connection on, so nothing else in the message is
// applied. Closed silently, like every other protocol error the receive path finds
// (see close_silently()).
conn->close_silently(SendspinGoodbyeReason::UNAUTHORIZED);
conn->close_silently();
break;
}
#endif
Expand Down Expand Up @@ -787,7 +783,7 @@ void SendspinClient::process_json_message(SendspinConnection& connection, const
// close_silently()). One the client had no memory to normalize closes it too,
// rather than applying the rest of the update under the previous group's id; on the
// next connection the server sends the group again after its first server/activate.
conn->close_silently(SendspinGoodbyeReason::UNAUTHORIZED);
conn->close_silently();
break;
}
if (group_msg.group_id_normalized && conn->note_group_id_normalized()) {
Expand Down
14 changes: 7 additions & 7 deletions src/connection.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -142,7 +142,7 @@ SsErr SendspinConnection::settle_noise_send(SsErr err) {
this->is_connected()) {
SS_LOGW(TAG, "Send failed after its frame was encrypted (err=%d); closing the connection",
static_cast<int>(err));
this->close_silently(SendspinGoodbyeReason::UNAUTHORIZED);
this->close_silently();
}
return err;
}
Expand Down Expand Up @@ -237,7 +237,7 @@ void SendspinConnection::send_noise_client_init() {
// No memory for the prologue: without client/init the peer never proceeds, so the
// connection would only hold its nursery slot until the establish deadline.
this->noise_handshake_.reset();
this->close_silently(SendspinGoodbyeReason::UNAUTHORIZED);
this->close_silently();
return;
}
#ifdef SENDSPIN_ENABLE_MESSAGE_TRACE
Expand Down Expand Up @@ -271,7 +271,7 @@ void SendspinConnection::handle_noise_handshake_text(std::string_view text) {
// connection.md "Failure Handling": a handshake-phase failure closes the WebSocket
// without sending any application-level message.
this->noise_handshake_.reset();
this->close_silently(SendspinGoodbyeReason::UNAUTHORIZED);
this->close_silently();
return;
}

Expand Down Expand Up @@ -424,7 +424,7 @@ SS_HOT SendspinConnection::InboundDispatch SendspinConnection::process_inbound_m
// connection.md "Failure Handling": a cleartext message after the switch to transport
// mode is a silent failure.
SS_LOGW(TAG, "TEXT frame in transport mode; closing connection");
this->close_silently(SendspinGoodbyeReason::UNAUTHORIZED);
this->close_silently();
return InboundDispatch::NONE;
}
SS_LOGW(TAG, "TEXT frame before the Noise handshake started; dropping");
Expand All @@ -439,7 +439,7 @@ SS_HOT SendspinConnection::InboundDispatch SendspinConnection::process_inbound_m
// with the Noise/PSK/admission chain bypassed. Treated as a handshake-phase failure
// per connection.md "Failure Handling": close without any application-level message.
SS_LOGW(TAG, "Binary frame before the Noise handshake completed; closing connection");
this->close_silently(SendspinGoodbyeReason::UNAUTHORIZED);
this->close_silently();
return InboundDispatch::NONE;
}
SS_LOGW(TAG, "Binary frame before the Noise handshake started; dropping");
Expand All @@ -456,7 +456,7 @@ SS_HOT SendspinConnection::InboundDispatch SendspinConnection::process_inbound_m
// advances the receive-direction nonce counter on an auth failure, so every later frame
// on this connection would fail authentication forever too.
SS_LOGW(TAG, "Noise AEAD failure in transport mode; closing connection");
this->close_silently(SendspinGoodbyeReason::UNAUTHORIZED);
this->close_silently();
return InboundDispatch::NONE;
}
// Route through the fragment state machine; hand any completed message to the caller.
Expand All @@ -466,7 +466,7 @@ SS_HOT SendspinConnection::InboundDispatch SendspinConnection::process_inbound_m
// A protocol error the receiver MUST close the connection for;
// NoiseTransport::CompleteMessage::malformed enumerates the cases that set it.
SS_LOGW(TAG, "Malformed binary message; closing connection");
this->close_silently(SendspinGoodbyeReason::UNAUTHORIZED);
this->close_silently();
return InboundDispatch::NONE;
}
if (reassembled.data == nullptr) {
Expand Down
4 changes: 2 additions & 2 deletions src/connection.h
Original file line number Diff line number Diff line change
Expand Up @@ -201,7 +201,7 @@ class SendspinConnection : public std::enable_shared_from_this<SendspinConnectio
/// "Noise_KKpsk2_25519_ChaChaPoly_SHA256"), or nullptr if none was set.
/// Used to select the AEAD cipher for pairing.md "Wrapping" (see
/// platform/crypto.h aead_cipher_name_from_noise_suite()).
virtual const char* get_noise_suite_name() const {
const char* get_noise_suite_name() const {
return this->noise_suite_name_;
}

Expand Down Expand Up @@ -337,7 +337,7 @@ class SendspinConnection : public std::enable_shared_from_this<SendspinConnectio
/// block on a transport join; see close_transport_now()). The inbound gate is detached first,
/// so nothing the peer sent after the failure is processed, and the protocol task reports the
/// loss.
void close_silently(SendspinGoodbyeReason /*reason*/) {
void close_silently() {
this->detach_inbound();
this->close_transport_now();
}
Expand Down
2 changes: 1 addition & 1 deletion src/connection_manager.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -1204,7 +1204,7 @@ uint32_t ConnectionManager::maybe_start_ws_server(int64_t now_us) {
this->ws_server_->set_discard_capacity(
std::max(ring != nullptr ? ring->largest_message_bytes() : INBOUND_MAX_MESSAGE_BYTES,
InboundGate::PRE_ADMISSION_MESSAGE_BYTES));
if (!this->ws_server_->start(this->client_, this->client_->config_.httpd_psram_stack,
if (!this->ws_server_->start(this->client_->config_.httpd_psram_stack,
this->client_->config_.httpd_priority,
this->client_->config_.httpd_stack_size)) {
// A persistent failure (e.g. the server port is already in use) is retried with backoff
Expand Down
2 changes: 1 addition & 1 deletion src/connection_manager_pairing.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -756,7 +756,7 @@ void ConnectionManager::close_on_malformed_message(SendspinConnection* conn) {
SendspinPairAbortReason::UNKNOWN);
return;
}
conn->close_silently(SendspinGoodbyeReason::UNAUTHORIZED);
conn->close_silently();
}

void ConnectionManager::close_on_sequence_violation(SendspinConnection* conn,
Expand Down
16 changes: 0 additions & 16 deletions src/crypto/pairing_code.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -58,22 +58,6 @@ std::optional<std::array<uint8_t, PAIRING_COMMIT_SIZE>> pairing_code_commit(cons
return commitment;
}

// ============================================================================
// pairing_code_verify_commit
// ============================================================================

bool pairing_code_verify_commit(const uint8_t* nonce, size_t nonce_len, const uint8_t* commitment,
size_t commitment_len) {
if (commitment_len != PAIRING_COMMIT_SIZE || nonce_len != PAIRING_NONCE_SIZE) {
return false;
}
auto computed = pairing_code_commit(nonce, nonce_len);
if (!computed.has_value()) {
return false;
}
return constant_time_equal(computed->data(), commitment, PAIRING_COMMIT_SIZE);
}

// ============================================================================
// pairing_code_digest
// ============================================================================
Expand Down
5 changes: 0 additions & 5 deletions src/crypto/pairing_code.h
Original file line number Diff line number Diff line change
Expand Up @@ -95,11 +95,6 @@ std::array<uint8_t, PAIRING_NONCE_SIZE> pairing_generate_nonce();
std::optional<std::array<uint8_t, PAIRING_COMMIT_SIZE>> pairing_code_commit(const uint8_t* nonce,
size_t nonce_len);

/// @brief Return true if SHA-256(PAIRING_COMMIT_LABEL || nonce) equals commitment
/// (constant-time)
bool pairing_code_verify_commit(const uint8_t* nonce, size_t nonce_len, const uint8_t* commitment,
size_t commitment_len);

/// @brief Derive the dynamic pairing code's digest from the Noise handshake hash and both nonces.
///
/// digest = SHA-256(PAIRING_CODE_DERIVE_LABEL || handshake_hash || nonce_a || nonce_b): the
Expand Down
6 changes: 2 additions & 4 deletions src/esp/ws_server.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -55,15 +55,13 @@ SendspinWsServer::~SendspinWsServer() {
this->stop();
}

bool SendspinWsServer::start(SendspinClient* client, bool task_stack_in_psram,
unsigned task_priority, size_t task_stack_size) {
bool SendspinWsServer::start(bool task_stack_in_psram, unsigned task_priority,
size_t task_stack_size) {
if (this->server_ != nullptr) {
SS_LOGW(TAG, "Server already started");
return true;
}

this->client_ = client;

// Configure the HTTP server
httpd_config_t config = HTTPD_DEFAULT_CONFIG();
if (task_stack_in_psram) {
Expand Down
11 changes: 1 addition & 10 deletions src/esp/ws_server.h
Original file line number Diff line number Diff line change
Expand Up @@ -34,10 +34,6 @@

namespace sendspin {

// Forward declarations
class SendspinClient;
class SendspinConnection;

/// @brief An accepted httpd session whose WebSocket upgrade has not yet been observed.
///
/// The session slot (SendspinWsServer::sessions_) remains the authoritative owner of the
Expand Down Expand Up @@ -92,14 +88,12 @@ class SendspinWsServer {
using WakeCallback = std::function<void()>;

/// @brief Starts the HTTP server and begins listening for WebSocket connections
/// @param client Pointer to the SendspinClient (used for context in callbacks).
/// @param task_stack_in_psram Whether to allocate the HTTP server task stack in PSRAM.
/// @param task_priority Priority for the HTTP server task.
/// @param task_stack_size HTTP server task stack size in bytes. Clamped up to
/// SendspinClientConfig::DEFAULT_HTTPD_STACK_SIZE if lower.
/// @return true if server started successfully, false otherwise.
bool start(SendspinClient* client, bool task_stack_in_psram, unsigned task_priority,
size_t task_stack_size);
bool start(bool task_stack_in_psram, unsigned task_priority, size_t task_stack_size);

/// @brief Stops the HTTP server
void stop();
Expand Down Expand Up @@ -244,9 +238,6 @@ class SendspinWsServer {

// Pointer fields

/// @brief Stored as the httpd user context for the static callbacks
SendspinClient* client_{nullptr};

httpd_handle_t server_{nullptr};

// Numeric fields
Expand Down
6 changes: 2 additions & 4 deletions src/host/ws_server.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -46,8 +46,8 @@ SendspinWsServer::~SendspinWsServer() {
this->stop();
}

bool SendspinWsServer::start(SendspinClient* client, bool /*task_stack_in_psram*/,
unsigned /*task_priority*/, size_t /*task_stack_size*/) {
bool SendspinWsServer::start(bool /*task_stack_in_psram*/, unsigned /*task_priority*/,
size_t /*task_stack_size*/) {
if (this->server_ != nullptr) {
SS_LOGW(TAG, "Server already started");
return true;
Expand All @@ -61,8 +61,6 @@ bool SendspinWsServer::start(SendspinClient* client, bool /*task_stack_in_psram*
return false;
}

this->client_ = client;

// Create IXWebSocket server on the configured port. max_connections_ is enforced here (IX
// closes surplus sockets at accept), so the configured budget is real on host, matching the
// ESP build's httpd max_open_sockets.
Expand Down
8 changes: 1 addition & 7 deletions src/host/ws_server.h
Original file line number Diff line number Diff line change
Expand Up @@ -30,8 +30,6 @@
namespace sendspin {

// Forward declarations
class SendspinClient;
class SendspinConnection;
class SendspinServerConnection;

/**
Expand Down Expand Up @@ -67,8 +65,7 @@ class SendspinWsServer {

/// @brief Starts the WebSocket server on the configured port; the three task parameters are
/// ESP-IDF httpd settings and are ignored here.
bool start(SendspinClient* client, bool task_stack_in_psram, unsigned task_priority,
size_t task_stack_size);
bool start(bool task_stack_in_psram, unsigned task_priority, size_t task_stack_size);

/// @brief Stops the WebSocket server and releases its resources
void stop();
Expand Down Expand Up @@ -129,9 +126,6 @@ class SendspinWsServer {

// Pointer fields

/// @brief Stored as the user context for the IX callbacks
SendspinClient* client_{nullptr};

std::unique_ptr<ix::WebSocketServer> server_;

// Numeric fields
Expand Down
4 changes: 2 additions & 2 deletions src/inbound_ring.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -247,7 +247,7 @@ bool InboundGate::wait_until_writable(uint32_t timeout_ms) {
}
wait_ms = static_cast<uint32_t>((remaining_us + US_PER_MS - 1) / US_PER_MS);
}
this->consumed_flags_.wait(CONSUMED, false, true, wait_ms);
this->consumed_flags_.wait(CONSUMED, true, wait_ms);
}
return true;
}
Expand Down Expand Up @@ -315,7 +315,7 @@ void* InboundItemList::take(uint32_t timeout_ms) {
// An append between the pop above and this wait has already set ITEMS_APPENDED, so the wait
// returns at once rather than missing it. A bit left by an append whose item an earlier pop
// took returns here with nothing to pop, which the caller treats as a retry.
this->flags_.wait(ITEMS_APPENDED | WAKE, false, true, timeout_ms);
this->flags_.wait(ITEMS_APPENDED | WAKE, true, timeout_ms);
return this->pop();
}

Expand Down
15 changes: 3 additions & 12 deletions src/inbound_ring.h
Original file line number Diff line number Diff line change
Expand Up @@ -343,11 +343,6 @@ class InboundRing {
bool create(size_t storage_bytes, MemoryLocation location,
size_t largest_message_bytes = INBOUND_MAX_MESSAGE_BYTES);

/// @brief Whether create() succeeded
bool is_created() const {
return this->ring_.is_created();
}

/// @brief The longest received message a transport writes into a ring item:
/// max_item_message_bytes() capped at INBOUND_MAX_MESSAGE_BYTES, since a conforming peer's
/// WebSocket message is at most one Noise frame. The derivation sizes the ring for the
Expand Down Expand Up @@ -591,7 +586,7 @@ class InboundItemList {
/// only.
/// @return The bits among `bits` that were set; 0 on timeout.
uint32_t take_signals(uint32_t bits, uint32_t timeout_ms) {
return this->flags_.wait(bits, false, true, timeout_ms) & bits;
return this->flags_.wait(bits, true, timeout_ms) & bits;
}

/// @brief Clears every bit. Before the consumer thread starts, while the list is empty.
Expand Down Expand Up @@ -1203,12 +1198,8 @@ static constexpr size_t INBOUND_MIN_AUDIO_FRAME_BYTES = 160;
/// Frames per second at INBOUND_MIN_AUDIO_FRAME_BYTES: one every 20 ms, Opus's default frame.
static constexpr size_t INBOUND_MIN_AUDIO_FRAMES_PER_SECOND = 50;

/// The lowest audio rate the library budgets for, in encoded bytes per second (64 kbit/s).
static constexpr size_t MIN_ADVERTISED_AUDIO_BYTES_PER_SECOND =
INBOUND_MIN_AUDIO_FRAME_BYTES * INBOUND_MIN_AUDIO_FRAMES_PER_SECOND;

/// Ring storage per second of audio at MIN_ADVERTISED_AUDIO_BYTES_PER_SECOND: each frame stored
/// as one item with its chunk header and the stored overhead.
/// Ring storage per second of INBOUND_MIN_AUDIO_FRAMES_PER_SECOND frames of
/// INBOUND_MIN_AUDIO_FRAME_BYTES, each stored as one item with its chunk header and overhead.
static constexpr size_t INBOUND_MIN_AUDIO_STORED_BYTES_PER_SECOND =
(INBOUND_MIN_AUDIO_FRAME_BYTES + INBOUND_AUDIO_CHUNK_HEADER_BYTES +
INBOUND_ITEM_STORED_OVERHEAD_BYTES) *
Expand Down
6 changes: 3 additions & 3 deletions src/noise_handshake.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -143,10 +143,10 @@ std::optional<Msg1CoreResult> run_msg1_core(HandshakeKind kind, const Identity&

// psk_id lives inside msg1's encrypted payload, so the PSK is not known yet when the
// session is built. KKpsk2 mixes the PSK only into msg2, so msg1 authenticates under the
// static keys alone (KK's "es"/"ss" tokens); build the responder with no PSK bound and
// defer that until it is resolved below (see NoiseSession::set_psk).
// static keys alone (KK's "es"/"ss" tokens); the PSK is bound once it is resolved below
// (see NoiseSession::set_psk).
auto session = NoiseSession::as_responder(suite_name, identity.private_bytes.data(),
server_pub->data(), prologue, prologue_len, nullptr);
server_pub->data(), prologue, prologue_len);
if (!session.has_value()) {
SS_LOGE(TAG, "%s: failed to build session", log_prefix);
return std::nullopt;
Expand Down
Loading
Loading