syncspin-client 0.1.0

Sendspin client: session loop, noise handshake, Sink trait and event stream
Documentation
# syncspin

A Rust library for [the Sendspin protocol](https://github.com/Sendspin/spec): a client today, a
server planned. A server owns the queue and the clock, clients render the audio and report their
state back.

[![CI](https://github.com/acuntex/syncspin/actions/workflows/ci.yml/badge.svg?branch=main)](https://github.com/acuntex/syncspin/actions/workflows/ci.yml)
[![License](https://img.shields.io/badge/license-MIT%20OR%20Apache--2.0-blue)](#licence)
[![MSRV](https://img.shields.io/badge/MSRV-1.85-blue)](https://github.com/acuntex/syncspin/blob/main/Cargo.toml)

## Status

**0.1, client first.** The client is implemented and covered by a hermetic test suite, including
pairing: the Pairing PSK flow, the records it writes, the in-band re-handshake and `server/unpair`,
plus the static and dynamic code flows behind the `pairing-code` feature. `syncspin-server` is a stub
with `publish = false`. Nothing is published on crates.io yet: the first upload waits on the account
side, and `v0.1.0` is a pre-release tag that marks the pinnable state. The API may change before 1.0. The CPace layer behind the code flows has not been reviewed
externally, so it is unaudited code until it has been.

`syncspin` is not an official Sendspin implementation and is not affiliated with the Sendspin
project; the name describes only the protocol the code speaks.

## Crates

| Path                      | Contents                                                                        |
| ------------------------- | ------------------------------------------------------------------------------- |
| `crates/syncspin-core/`   | Noise handshake, framing, messages, clock filter. No transport, no device code. |
| `crates/syncspin-client/` | Session loop, `Sink` trait, event stream, pairing and its `Storage` trait.      |
| `crates/syncspin-server/` | Planned for 0.2: listener, streams, roles, pairing.                             |
| `examples/player-pipe/`   | Runnable reference player: PCM on stdout, status lines on stderr, pairing.      |

`syncspin-core` never depends on `syncspin-client` or `syncspin-server`; every protocol and crypto
decision lives in one place.

## Getting started

The crates are not on crates.io yet. Pairing landed after the `v0.1.0` tag, so depend on `main`
until the first registry release exists:

```toml
[dependencies]
syncspin-client = { git = "https://github.com/acuntex/syncspin", branch = "main" }
```

`v0.1.0` predates pairing: a client pinned there is a guest only. Pin a tag instead of `main` once
one carries the features you need.

The example player needs a Sendspin server to talk to:

```sh
cargo run -p player-pipe -- --server music-assistant.local:8927 | aplay -f S16_LE -r 48000 -c 2
```

Run `cargo run -p player-pipe -- --help` for the player name, the identity file and the pairing
store. The first run writes `./identity.key` and `./pairing.json` with owner-only permissions; later
runs reuse both. To pair the player, print its version-0 pairing token and enter it in the server:

```sh
cargo run -p player-pipe -- --pairing-token
```

The token is a credential: whoever holds it can pair a server with this client, so hand it over
directly and keep it out of logs and issues. A server that admits unpaired clients still accepts the
player as a guest. `--features pairing-code` adds `--static-code` and `--open-window` for the static
code flow.

The example's source is meant to be read: `src/main.rs` holds the event loop, the identity handling
and the pairing token, `src/pipe_sink.rs` the `Sink` implementation.

## What works today

A connection reconnects on its own: when an attempt ends, the crate flushes the sink, reports
`Event::Disconnected` with the delay it applies (2 s at first, doubling up to
`ClientConfig::max_backoff`, and 1 s again after a session that connected) and tries again with the
same sink, identity, volume and mute state. It stops only when the audio sink fails or when the
handle or event stream is dropped.

`ClientConfig::volume` and `ClientConfig::muted` are the level and mute state the first `client/state`
carries. A host passes the values it restored, so the server never sees an invented baseline; a host
without stored values passes `100` and `false`. `ControlHandle::set_volume` returns the level that
was applied, and `ControlHandle::volume` reports the level in force without a call.

`ClientConfig::volume_policy` limits a request from the server or from the host. The default policy
is the rule `clamp_volume` implements: a request to 40 or below is applied as asked, and above 40 one
request may raise the level by at most 20. `clamp_volume_with` takes a policy, for a device that needs
a different guard. `Event::Volume` carries both the requested and the applied level, and the
`client/state` report carries the applied one.

`ControlHandle::report_volume` is the other direction: a host that reads the level its output is
actually at - because the device applied one at its own control, or because another process changed
it - reports it, and the next `client/state` carries it unchanged. The policy limits requests, not
the level the device is at, so a device the user raised to 70 while the threshold is 40 reports 70.
A level above the protocol maximum of 100 is refused and nothing is recorded or sent.

`ClientConfig::device_info` describes the machine the client runs on - product name, manufacturer,
software version and MAC address - and is announced in `client/hello`, so the server can show the
hardware rather than only the player name. A host that describes no device passes `None`.

The stream lifecycle is visible on the event stream: `Event::StreamStart` announces a new format,
`Event::StreamEnd` reports a pause or a removed player role, and `Event::StreamClear` reports a seek
with its timestamp. The end and clear events arrive before the client flushes the sink, so a host can
mute, stop or restart its output first; a reconnect flush produces no stream event. `Event::Track`
carries the now-playing metadata with the position, the duration and the playback speed in per-mille,
where `1000` is normal speed.

## Pairing

Pairing belongs to the host: it supplies a [`Storage`](crates/syncspin-client/src/storage.rs) with the
pairing PSK, the records of servers it has paired with, and the calls that read and write them. The
crate draws and persists the PSK on the first run, offers the Pairing PSK method on every connection,
and writes a record after `server/pair-finalize`; `Event::Paired` reports it. A record authenticates
the next connection, and the session survives the server's in-band re-handshake without dropping the
stream. `server/unpair` removes the record and arrives as `Event::Unpaired`; a server that names a
`psk_id` the client does not hold produces `Event::PairingRequired` once per connection. Without a
store the client offers no pairing method and runs as a guest — unless the host passes records
through `connect_with_psks`, which needs no store and still authenticates against them.

`FileStorage` is the optional JSON backend behind the `storage-file` feature, and the example uses
it. The crate writes at most five records into a store it manages, evicting the oldest first and
never the record backing the live connection; a store that already holds more is read as it is. That
order is insertion order, not use order, so a record kept since long ago can be evicted before one
used recently. `Storage::store_pairing` is the primitive, not the whole rule: calling it directly
skips the live-record pin, and `FileStorage` trims to five there only as a safety net while a host
backend may not trim at all. A host that writes a record itself calls the exported `persist_pairing`,
which applies both rules to any store, instead of reimplementing them.

With the `pairing-code` feature the client also runs the static and dynamic code flows, gated by a
pairing window the host opens or by the process-wide round limit. The dynamic flow shows the operator
a six-digit code or a version-1 token; both flows deliver the long-term key sealed under the CPace
output. The CPace layer is unaudited — see [Status](#status).

## What does not work yet

- **Pairing control surface.** There is no `ControlHandle::pairing_token()`, so a host that wants the
  operator-facing `SP:` token assembles it from the identity's public key and `Storage::pairing_psk()`
  with the encoder in `syncspin_core::pairing::token` — `player-pipe --pairing-token` does exactly
  that. There is no `client/goodbye` writer, so a graceful close carries no reason and
  `concurrent_attempt` cannot be sent as a goodbye reason; with one connection that reason is
  unreachable anyway. Unpaired access is always admitted, and nothing turns it off.
- **Server.** `syncspin-server` is a stub; the listener, streams, roles and pairing server arrive in
  0.2.
- **Discovery.** Clients do not advertise over mDNS and do not accept server-initiated connections.
- **Group state.** `group/update`, the spec's authoritative source of the playback state, is not
  handled.
- **TLS.** No TLS stack: a `wss://` address is rejected when the client is configured, and nothing
  is downgraded to `ws://`. A TLS backend is out of scope for 0.1.

Pairing, discovery, `group/update` and the other departures from the specification are tracked with
their reasons and the work that closes them in [docs/spec-deviations.md](docs/spec-deviations.md).
The server half is not a deviation — it is staged work for 0.2.

## Integrating a client

A host supplies a [`Sink`](crates/syncspin-client/src/sink.rs): `open` for a new format, `write` for
every chunk with the playout deadline the client computed, `flush` at each boundary the crate
announces, and optionally `latency` and `underruns` so the client can hold its buffer and report
timing. The crate owns the connection, the clock and the reconnect loop; the host owns the output
device, the identity file and everything below the pipe. Pairing needs a
[`Storage`](crates/syncspin-client/src/storage.rs) as well; without one the client offers no pairing
method, and a host that already holds records can pass them to `connect_with_psks` instead.

```rust
let (handle, mut events) = Client::connect(config, Box::new(my_sink)).await?;
while let Some(event) = events.next().await {
    // StreamStart, StreamEnd, StreamClear, Track, Volume, Disconnected, ...
}
```

`handle.control()` returns the play/pause/skip, volume and mute controls; dropping the handle or the
event stream ends the connection.

## Integrating a server

`syncspin-server` is a stub and is not published. It is where the listener, the stream handling, the
roles and the server side of pairing will live for 0.2, and its shape is described in
[docs/design/syncspin-design.md](docs/design/syncspin-design.md). Until then, build the client side
and use a Sendspin server you already have.

## Related projects

Nothing to list yet. A sibling open-source client built on `syncspin-client` will be linked here
once it is public.

## Documentation

[`docs/`](docs/README.md) indexes the protocol design, every known spec deviation and the testing
handbook.

## Requirements

- **MSRV 1.85**, edition 2021.
- On the ARMv7 / glibc 2.24 target build with
  `cargo zigbuild --target armv7-unknown-linux-gnueabihf`. `openssl` and `ring` are out: the crypto
  stack is `snow`, `x25519-dalek`, `elligator2` and the RustCrypto primitives (`chacha20poly1305`,
  `sha2`, `hmac`) the pairing code flows need.

## Licence

MIT OR Apache-2.0, at your option. See [LICENSE-MIT](LICENSE-MIT) and
[LICENSE-APACHE](LICENSE-APACHE).