syncspin_core/messages.rs
1//! Sendspin wire messages.
2//!
3//! Every JSON message is an envelope of the form `{"type": "<group>/<name>", "payload": {..}}`.
4//! [`Incoming`] classifies one such envelope: deserializing it reads `type` and parses `payload`
5//! into the matching struct, and serializing a variant writes the envelope back, so a session
6//! needs one type for both directions.
7//!
8//! The opening messages of a connection — `client/init`, `server/init` and `noise/handshake` —
9//! travel as cleartext text before the Noise handshake; every later JSON message travels inside a
10//! Noise transport message with binary message id `0`. The structs here do not know which phase
11//! they belong to.
12//!
13//! Parsing is lenient in the direction a receiver needs it: unknown fields are ignored, and
14//! fields the specification allows to be absent default. A `type` this revision does not define
15//! is an error, never a silent default, so the caller decides whether to ignore the message.
16
17use std::fmt;
18
19use anyhow::{bail, Result};
20use serde::{Deserialize, Serialize};
21
22/// Core message format version carried by `client/init` and `server/init`.
23///
24/// Both sides send `1`; a peer that sends another value is speaking a different core format.
25pub const PROTOCOL_VERSION: u32 = 1;
26
27/// Noise cipher suite name carried by `client/init`.
28///
29/// This is the suite the client of this library announces,
30/// [`Suite::ChaChaPoly`](crate::noise::Suite::ChaChaPoly). A server MUST support both suites in
31/// [`Suite::ALL`](crate::noise::Suite::ALL), so the choice lives with the client and the server
32/// reads it from `client/init` rather than negotiating.
33pub const NOISE_SUITE: &str = crate::noise::Suite::ChaChaPoly.wire_name();
34
35/// Binary message id of a player audio chunk.
36pub const AUDIO_CHUNK_ID: u8 = 4;
37
38// ---------------------------------------------------------------------------
39// Handshake: cleartext, before the Noise transport
40// ---------------------------------------------------------------------------
41
42/// `client/init`: the client's opening message on a connection.
43///
44/// `client_id` is the client's static X25519 public key, base64url-encoded without padding, and
45/// stays the same across reconnections so a server can recognise the client. `suite` names the
46/// Noise cipher suite the client picked for this connection.
47#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
48#[serde(rename_all = "snake_case")]
49pub struct ClientInit {
50 /// Static public key as 43 base64url characters without padding.
51 pub client_id: String,
52 /// Core message format version, [`PROTOCOL_VERSION`].
53 pub version: u32,
54 /// Noise cipher suite, [`NOISE_SUITE`].
55 pub suite: String,
56}
57
58/// `server/init`: the server's answer to [`ClientInit`].
59///
60/// The server sends it immediately, followed by the first `noise/handshake` message, without
61/// waiting for anything in between.
62#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
63#[serde(rename_all = "snake_case")]
64pub struct ServerInit {
65 /// Static public key as 43 base64url characters without padding.
66 pub server_id: String,
67 /// Core message format version, [`PROTOCOL_VERSION`].
68 pub version: u32,
69}
70
71/// `server/error`: the server rejected the client's [`ClientInit`] and closes the connection.
72///
73/// Sent in place of [`ServerInit`] when the server cannot accept `client/init` (`connection.md`,
74/// _Failure Handling_), before the Noise handshake starts. `reason` is one of
75/// `unsupported_version`, `unsupported_suite` or `malformed`; an unknown value is carried verbatim
76/// rather than rejected, so a later revision's reason reaches the caller instead of being read as a
77/// decoding failure. The message is unauthenticated: its reason is a hint for logging and operator
78/// display, not a verified fact.
79#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
80#[serde(rename_all = "snake_case")]
81pub struct ServerError {
82 /// Why the server refused the init, for example `unsupported_version`.
83 pub reason: String,
84}
85
86/// `noise/handshake`: one Noise handshake message.
87///
88/// The server sends the first message right after [`ServerInit`]; the client answers with the
89/// second and last one. The bytes travel base64url-encoded without padding.
90#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
91#[serde(rename_all = "snake_case")]
92pub struct NoiseHandshake {
93 /// One Noise handshake message as base64url characters without padding.
94 pub data: String,
95}
96
97// ---------------------------------------------------------------------------
98// Client capabilities: client/hello
99// ---------------------------------------------------------------------------
100
101/// The `device_info` object of [`ClientHello`].
102///
103/// Every field is optional and plain text of at most 64 bytes in UTF-8.
104#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)]
105#[serde(rename_all = "snake_case")]
106pub struct DeviceInfo {
107 /// Device model or product name.
108 #[serde(default, skip_serializing_if = "Option::is_none")]
109 pub product_name: Option<String>,
110 /// Device manufacturer.
111 #[serde(default, skip_serializing_if = "Option::is_none")]
112 pub manufacturer: Option<String>,
113 /// Software version of the client, not the protocol version.
114 #[serde(default, skip_serializing_if = "Option::is_none")]
115 pub software_version: Option<String>,
116 /// Network interface MAC address as lowercase colon-separated bytes.
117 #[serde(default, skip_serializing_if = "Option::is_none")]
118 pub mac_address: Option<String>,
119}
120
121/// One audio format a player advertises in [`PlayerSupport::supported_formats`].
122#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
123#[serde(rename_all = "snake_case")]
124pub struct SupportedFormat {
125 /// Codec identifier: `opus`, `flac` or `pcm`.
126 pub codec: String,
127 /// Number of channels.
128 pub channels: u8,
129 /// Sample rate in hertz.
130 pub sample_rate: u32,
131 /// Bit depth; meaningful for `pcm` and `flac` only.
132 pub bit_depth: u8,
133}
134
135/// The `player@v1_support` object of [`ClientHello`].
136#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
137#[serde(rename_all = "snake_case")]
138pub struct PlayerSupport {
139 /// Supported formats in priority order, most preferred first.
140 pub supported_formats: Vec<SupportedFormat>,
141 /// Largest total size in bytes of outstanding audio chunks.
142 pub buffer_capacity: u64,
143}
144
145/// The `pairing_psk` descriptor of [`SupportedPairMethods`].
146///
147/// The method carries no parameters, so the descriptor is the empty object.
148#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, Serialize, Deserialize)]
149#[serde(rename_all = "snake_case")]
150pub struct PairingPskMethod {}
151
152/// The `static_pairing_code` descriptor of [`SupportedPairMethods`].
153///
154/// The only field is an informational hint: where the operator finds the configured code. A client
155/// that does not know leaves it absent, and the descriptor serializes as the empty object.
156#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)]
157#[serde(rename_all = "snake_case")]
158pub struct StaticPairingCodeMethod {
159 /// Where the code is available: `device`, `leaflet` or `operator`.
160 #[serde(default, skip_serializing_if = "Option::is_none")]
161 pub locations: Option<Vec<String>>,
162}
163
164/// The `dynamic_pairing_code` descriptor of [`SupportedPairMethods`].
165///
166/// The protocol requires both lists to be non-empty for a server to recognize the method: a
167/// descriptor left empty is treated as unrecognized, so the client only advertises it when it can
168/// actually emit a code.
169#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)]
170#[serde(rename_all = "snake_case")]
171pub struct DynamicPairingCodeMethod {
172 /// Channels that carry the per-session code to the operator: `display` or `speaker`.
173 pub out_channels: Vec<String>,
174 /// Emission formats the client offers: `digits` or `qr_code`.
175 pub formats: Vec<String>,
176}
177
178/// The `supported_pair_methods` object of [`ClientHello`], keyed by method identifier.
179#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)]
180#[serde(rename_all = "snake_case")]
181pub struct SupportedPairMethods {
182 /// The pairing PSK method, offered by every conformant client; absent when a peer omits it.
183 #[serde(default, skip_serializing_if = "Option::is_none")]
184 pub pairing_psk: Option<PairingPskMethod>,
185 /// The static pairing code method, offered when the client has a code configured.
186 #[serde(default, skip_serializing_if = "Option::is_none")]
187 pub static_pairing_code: Option<StaticPairingCodeMethod>,
188 /// The dynamic pairing code method, offered when the client can derive and emit a code.
189 #[serde(default, skip_serializing_if = "Option::is_none")]
190 pub dynamic_pairing_code: Option<DynamicPairingCodeMethod>,
191}
192
193/// The `unpaired_access` object of [`ClientHello`].
194#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)]
195#[serde(rename_all = "snake_case")]
196pub struct UnpairedAccess {
197 /// Whether the client currently admits unpaired access.
198 #[serde(default)]
199 pub enabled: bool,
200}
201
202/// `client/hello`: the client's roles and capabilities.
203///
204/// Sent once per connection, after [`ServerHello`]. A role listed in `supported_roles` that
205/// defines a support object must carry it; `player@v1` requires
206/// [`player_support`](Self::player_support).
207#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
208#[serde(rename_all = "snake_case")]
209pub struct ClientHello {
210 /// Friendly name of the client, plain text of at most 64 bytes in UTF-8.
211 pub name: String,
212 /// Optional description of the device.
213 #[serde(default, skip_serializing_if = "Option::is_none")]
214 pub device_info: Option<DeviceInfo>,
215 /// Versioned role identifiers the client supports, for example `player@v1`.
216 pub supported_roles: Vec<String>,
217 /// Player capabilities; present exactly when `player@v1` is listed.
218 #[serde(
219 rename = "player@v1_support",
220 default,
221 skip_serializing_if = "Option::is_none"
222 )]
223 pub player_support: Option<PlayerSupport>,
224 /// Pairing methods the client currently offers.
225 pub supported_pair_methods: SupportedPairMethods,
226 /// Whether the client currently admits unpaired access.
227 pub unpaired_access: UnpairedAccess,
228}
229
230// ---------------------------------------------------------------------------
231// Server handshake: server/hello and server/activate
232// ---------------------------------------------------------------------------
233
234/// `server/hello`: the server's identity, the first message after the handshake.
235#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
236#[serde(rename_all = "snake_case")]
237pub struct ServerHello {
238 /// Friendly name of the server, plain text of at most 64 bytes in UTF-8.
239 #[serde(default)]
240 pub name: String,
241 /// BCP 47 language tags the operator understands, most preferred first.
242 #[serde(default, skip_serializing_if = "Option::is_none")]
243 pub languages: Option<Vec<String>>,
244}
245
246/// The `pairing` object of [`ServerActivate`].
247#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
248#[serde(rename_all = "snake_case")]
249pub struct PairingActivation {
250 /// Pairing method the server picked from the client's offered set.
251 pub method: String,
252 /// Emission format of a dynamic pairing code; absent for other methods.
253 #[serde(default, skip_serializing_if = "Option::is_none")]
254 pub format: Option<String>,
255}
256
257/// `server/activate`: the server's purpose on this connection and the active roles.
258///
259/// The first activation of a connection declares the roles the client may use. Later ones may
260/// omit `active_roles`, which leaves the previous set in force.
261#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)]
262#[serde(rename_all = "snake_case")]
263pub struct ServerActivate {
264 /// Currently active purposes: `playback`, `pairing`, or none.
265 #[serde(default)]
266 pub activities: Vec<String>,
267 /// Versioned roles active for this client; absent keeps the previous set.
268 #[serde(default, skip_serializing_if = "Option::is_none")]
269 pub active_roles: Option<Vec<String>>,
270 /// Parameters of an admitted pairing attempt; present only with `pairing` activity.
271 #[serde(default, skip_serializing_if = "Option::is_none")]
272 pub pairing: Option<PairingActivation>,
273}
274
275// ---------------------------------------------------------------------------
276// Pairing
277// ---------------------------------------------------------------------------
278
279/// `client/pair-init`: starts a pairing attempt.
280///
281/// The Pairing PSK flow leaves `commit_B` absent. The Dynamic Pairing Code Flow requires it: the
282/// commitment locks the client's nonce before any value from the server is known. The Static
283/// Pairing Code Flow has no nonce of its own and leaves it absent as well.
284#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)]
285#[serde(rename_all = "snake_case")]
286pub struct ClientPairInit {
287 /// Number of pairing `server/activate` messages received since the last Noise handshake.
288 pub pairing_index: u32,
289 /// `SHA-256(label || nonce_B)` of the dynamic flow's client nonce, when the method needs one.
290 ///
291 /// The wire spells the field `commit_B`, so the rename is explicit.
292 #[serde(rename = "commit_B", default, skip_serializing_if = "Option::is_none")]
293 pub commit_b: Option<String>,
294}
295
296/// `server/pair-init`: begins a round of the Dynamic Pairing Code Flow.
297///
298/// The server sends it in answer to `client/pair-init`, and again after every
299/// [`ClientPairRetry`]. Only the first round carries the server's nonce: the binding values, and
300/// with them the code, are unchanged across the rounds of one attempt.
301#[derive(Clone, Default, PartialEq, Eq, Serialize, Deserialize)]
302#[serde(rename_all = "snake_case")]
303pub struct ServerPairInit {
304 /// 32-byte server nonce as 43 unpadded base64url characters; present in the first round only.
305 ///
306 /// The value is public - it is the server's half of the code binding - and is renamed to the
307 /// `nonce_A` the wire spells. `Debug` redacts it anyway, so that no pairing message can carry
308 /// a nonce into a log line.
309 #[serde(rename = "nonce_A", default, skip_serializing_if = "Option::is_none")]
310 pub nonce_a: Option<String>,
311}
312
313impl fmt::Debug for ServerPairInit {
314 /// Formats the message with the server nonce redacted.
315 fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
316 formatter
317 .debug_struct("ServerPairInit")
318 .field("nonce_A", &redacted(&self.nonce_a))
319 .finish()
320 }
321}
322
323/// `client/pair-retry`: asks for another round of the dynamic flow.
324///
325/// Sent in place of [`ClientPairConfirm`] when `server_kc` did not verify and the round limit still
326/// admits another round. The payload is the empty object.
327#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)]
328#[serde(rename_all = "snake_case")]
329pub struct ClientPairRetry {}
330
331/// `client/pair-finalize`: the long-term PSK this pairing establishes.
332///
333/// Exactly one of the two fields is present: `long_term_psk` in the Pairing PSK flow, where the
334/// key travels inside the authenticated channel, and `wrapped_psk` in the code flows, where it is
335/// sealed under the CPace output. Both fields are key material, so `Debug` redacts them.
336#[derive(Clone, Default, PartialEq, Eq, Serialize, Deserialize)]
337#[serde(rename_all = "snake_case")]
338pub struct ClientPairFinalize {
339 /// 32-byte long-term PSK as 43 base64url characters without padding.
340 #[serde(default, skip_serializing_if = "Option::is_none")]
341 pub long_term_psk: Option<String>,
342 /// 48-byte sealed long-term PSK as 64 base64url characters without padding.
343 #[serde(default, skip_serializing_if = "Option::is_none")]
344 pub wrapped_psk: Option<String>,
345}
346
347impl fmt::Debug for ClientPairFinalize {
348 /// Formats the message with both key fields redacted.
349 ///
350 /// `long_term_psk` and `wrapped_psk` are key material: the first is the new long-term PSK
351 /// itself and the second seals it. A `Debug` log of a decoded message, including one reached
352 /// through [`Incoming`], therefore prints `<redacted>` and never the value.
353 fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
354 formatter
355 .debug_struct("ClientPairFinalize")
356 .field("long_term_psk", &redacted(&self.long_term_psk))
357 .field("wrapped_psk", &redacted(&self.wrapped_psk))
358 .finish()
359 }
360}
361
362/// Renders a key field as `Some("<redacted>")`, or `None` when the field is absent.
363fn redacted(value: &Option<String>) -> Option<&'static str> {
364 value.as_ref().map(|_| "<redacted>")
365}
366
367/// `server/pair-finalize`: the server persisted its pairing record.
368///
369/// The payload is the empty object; the message is the client's signal to persist its own record.
370#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)]
371#[serde(rename_all = "snake_case")]
372pub struct ServerPairFinalize {}
373
374/// `server/unpair`: the server dropped its pairing record for this client.
375///
376/// The payload is the empty object, the same shape as [`ServerPairFinalize`]. The message means the
377/// server no longer holds the long-term PSK that authenticates this client, so the client removes
378/// its own record and closes the connection. It is valid under any activity set, and a client on an
379/// unpaired session - one keyed by the Sentinel key or by its pairing PSK - ignores it.
380#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)]
381#[serde(rename_all = "snake_case")]
382pub struct ServerUnpair {}
383
384/// `client/pair-pending`: the client is holding the admitted attempt back.
385///
386/// Sent instead of [`ClientPairInit`] while the static flow's pairing window is closed, or while
387/// the dynamic flow's round limit holds attempts back. It neither starts the attempt nor its
388/// timeout, so a `pairing_index` here may be followed by an init carrying the same value later.
389#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
390#[serde(rename_all = "snake_case")]
391pub struct ClientPairPending {
392 /// Number of pairing `server/activate` messages received since the last Noise handshake.
393 pub pairing_index: u32,
394 /// Short sentence for the operator, supplied by the host.
395 ///
396 /// The spec allows at most 200 bytes of UTF-8; the client sends what its configuration holds.
397 #[serde(default, skip_serializing_if = "Option::is_none")]
398 pub message: Option<String>,
399}
400
401/// `server/pair-auth`: the server's CPace public share `Ya`.
402#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
403#[serde(rename_all = "snake_case")]
404pub struct ServerPairAuth {
405 /// 32-byte share as 43 base64url characters without padding.
406 pub pake_msg_1: String,
407}
408
409/// `client/pair-auth`: the client's CPace public share `Yb`.
410#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
411#[serde(rename_all = "snake_case")]
412pub struct ClientPairAuth {
413 /// 32-byte share as 43 base64url characters without padding.
414 pub pake_msg_2: String,
415}
416
417/// `server/pair-confirm`: the server's MCF tag `Ta`.
418///
419/// The tag is derived from the CPace session key, so `Debug` redacts it: no log line or failed
420/// assertion prints it.
421#[derive(Clone, PartialEq, Eq, Serialize, Deserialize)]
422#[serde(rename_all = "snake_case")]
423pub struct ServerPairConfirm {
424 /// 64-byte HMAC-SHA-512 tag as 86 base64url characters without padding.
425 pub server_kc: String,
426}
427
428impl fmt::Debug for ServerPairConfirm {
429 /// Formats the message with the key-confirmation tag redacted.
430 fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
431 formatter
432 .debug_struct("ServerPairConfirm")
433 .field("server_kc", &"<redacted>")
434 .finish()
435 }
436}
437
438/// `client/pair-confirm`: the client's MCF tag `Tb`, plus the dynamic flow's sealed opening.
439///
440/// Both fields are derived from the CPace session key, so `Debug` redacts them.
441#[derive(Clone, PartialEq, Eq, Serialize, Deserialize)]
442#[serde(rename_all = "snake_case")]
443pub struct ClientPairConfirm {
444 /// 64-byte HMAC-SHA-512 tag as 86 base64url characters without padding.
445 pub client_kc: String,
446 /// 48-byte sealing of `nonce_B`, present only in the Dynamic Pairing Code Flow.
447 ///
448 /// The wire spells the field `wrapped_nonce_B`, so the rename is explicit.
449 #[serde(
450 rename = "wrapped_nonce_B",
451 default,
452 skip_serializing_if = "Option::is_none"
453 )]
454 pub wrapped_nonce_b: Option<String>,
455}
456
457impl fmt::Debug for ClientPairConfirm {
458 /// Formats the message with the tag and the sealed nonce redacted.
459 fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
460 formatter
461 .debug_struct("ClientPairConfirm")
462 .field("client_kc", &"<redacted>")
463 .field("wrapped_nonce_B", &redacted(&self.wrapped_nonce_b))
464 .finish()
465 }
466}
467
468/// `pair/abort`: ends a pairing attempt, whether or not it started.
469///
470/// Both directions send it. The reason is one of the values `pairing.md` defines; an unknown
471/// value is carried verbatim rather than treated as a decoding failure, so a later revision's
472/// reason does not end the connection.
473#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
474#[serde(rename_all = "snake_case")]
475pub struct PairAbort {
476 /// Why the attempt ended, for example `attempt_timeout` or `method_not_supported`.
477 pub reason: String,
478}
479
480// ---------------------------------------------------------------------------
481// Clock synchronization
482// ---------------------------------------------------------------------------
483
484/// `client/time`: a clock-synchronization request.
485#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
486#[serde(rename_all = "snake_case")]
487pub struct ClientTime {
488 /// Client clock timestamp in microseconds at which the request was sent.
489 pub client_transmitted: i64,
490}
491
492/// `server/time`: the reply to [`ClientTime`], carrying the four timestamps of one measurement.
493#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
494#[serde(rename_all = "snake_case")]
495pub struct ServerTime {
496 /// Value of `client_transmitted` from the request.
497 pub client_transmitted: i64,
498 /// Server clock time in microseconds at which the request arrived.
499 pub server_received: i64,
500 /// Server clock time in microseconds at which this reply was sent.
501 pub server_transmitted: i64,
502}
503
504// ---------------------------------------------------------------------------
505// State
506// ---------------------------------------------------------------------------
507
508/// The `player` object of [`ClientState`].
509#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
510#[serde(rename_all = "snake_case")]
511pub struct PlayerState {
512 /// Volume in the range 0-100; required when `volume` is in `supported_commands`.
513 #[serde(default, skip_serializing_if = "Option::is_none")]
514 pub volume: Option<u8>,
515 /// Mute state; required when `mute` is in `supported_commands`.
516 #[serde(default, skip_serializing_if = "Option::is_none")]
517 pub muted: Option<bool>,
518 /// Output delay in milliseconds, compensating for delay beyond the audio port.
519 pub output_delay_ms: u32,
520 /// Minimum startup lead time in milliseconds.
521 pub required_lead_time_ms: u32,
522 /// Requested minimum ongoing buffer duration in milliseconds.
523 pub min_buffer_ms: u32,
524 /// Player commands the server may send: `volume`, `mute` and `set_output_delay`.
525 #[serde(default)]
526 pub supported_commands: Vec<String>,
527 /// Preferred audio format, one of the entries of
528 /// [`PlayerSupport::supported_formats`]; absent means no preference.
529 #[serde(default, skip_serializing_if = "Option::is_none")]
530 pub format: Option<SupportedFormat>,
531}
532
533/// `client/state`: client availability plus the state of each active role.
534///
535/// A role object that is absent keeps its previous state.
536#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
537#[serde(rename_all = "snake_case")]
538pub struct ClientState {
539 /// Whether the client is available to take part in playback.
540 pub available: bool,
541 /// Player state; present exactly when the `player` role is active.
542 #[serde(default, skip_serializing_if = "Option::is_none")]
543 pub player: Option<PlayerState>,
544}
545
546/// The `progress` object of [`Metadata`]. Times and durations are milliseconds.
547#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)]
548#[serde(rename_all = "snake_case")]
549pub struct Progress {
550 /// Position within the track.
551 #[serde(default, skip_serializing_if = "Option::is_none")]
552 pub track_progress: Option<u64>,
553 /// Length of the track; zero for a stream of unknown length.
554 #[serde(default, skip_serializing_if = "Option::is_none")]
555 pub track_duration: Option<u64>,
556 /// Playback speed per mille, `1000` at normal speed and `0` while paused.
557 #[serde(default, skip_serializing_if = "Option::is_none")]
558 pub playback_speed: Option<u32>,
559}
560
561/// The `metadata` object of [`ServerState`].
562#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)]
563#[serde(rename_all = "snake_case")]
564pub struct Metadata {
565 /// Server clock time in microseconds at which this metadata becomes valid.
566 #[serde(default, skip_serializing_if = "Option::is_none")]
567 pub timestamp: Option<i64>,
568 /// Track title.
569 #[serde(default, skip_serializing_if = "Option::is_none")]
570 pub title: Option<String>,
571 /// Track artist.
572 #[serde(default, skip_serializing_if = "Option::is_none")]
573 pub artist: Option<String>,
574 /// Album artist.
575 #[serde(default, skip_serializing_if = "Option::is_none")]
576 pub album_artist: Option<String>,
577 /// Album title.
578 #[serde(default, skip_serializing_if = "Option::is_none")]
579 pub album: Option<String>,
580 /// URL of the artwork image.
581 #[serde(default, skip_serializing_if = "Option::is_none")]
582 pub artwork_url: Option<String>,
583 /// Release year.
584 #[serde(default, skip_serializing_if = "Option::is_none")]
585 pub year: Option<i32>,
586 /// Track number within its album.
587 #[serde(default, skip_serializing_if = "Option::is_none")]
588 pub track: Option<u32>,
589 /// Playback progress; absent clears the known position.
590 #[serde(default, skip_serializing_if = "Option::is_none")]
591 pub progress: Option<Progress>,
592}
593
594/// The `controller` object of [`ServerState`].
595#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)]
596#[serde(rename_all = "snake_case")]
597pub struct ControllerState {
598 /// Media commands the group currently accepts.
599 #[serde(default)]
600 pub supported_commands: Vec<String>,
601 /// Volume of the whole group in the range 0-100.
602 #[serde(default, skip_serializing_if = "Option::is_none")]
603 pub volume: Option<u8>,
604 /// Mute state of the whole group.
605 #[serde(default, skip_serializing_if = "Option::is_none")]
606 pub muted: Option<bool>,
607 /// Repeat mode: `off`, `one` or `all`.
608 #[serde(default, skip_serializing_if = "Option::is_none")]
609 pub repeat: Option<String>,
610 /// Whether shuffle is enabled.
611 #[serde(default, skip_serializing_if = "Option::is_none")]
612 pub shuffle: Option<bool>,
613 /// Maximum absolute position a `seek` may target, in milliseconds.
614 ///
615 /// A server that advertises `seek` includes it; absent means the server offers no absolute seek
616 /// position, so only `seek_relative` is meaningful.
617 #[serde(default, skip_serializing_if = "Option::is_none")]
618 pub seek_max_ms: Option<u64>,
619}
620
621/// `server/state`: the state of each active server role.
622///
623/// A role object that is absent keeps its previous state.
624#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)]
625#[serde(rename_all = "snake_case")]
626pub struct ServerState {
627 /// Metadata state; present exactly when the `metadata` role is active.
628 #[serde(default, skip_serializing_if = "Option::is_none")]
629 pub metadata: Option<Metadata>,
630 /// Controller state; present exactly when the `controller` role is active.
631 #[serde(default, skip_serializing_if = "Option::is_none")]
632 pub controller: Option<ControllerState>,
633}
634
635/// `group/update`: the state and identity of the group this client is part of.
636///
637/// The server sends it after the first `server/activate` and whenever one of the fields changes,
638/// and every message carries all three. `server/state` carries only the role objects, so a client
639/// that wants the group's playback state has no other source. `group_id` that is not 43 unpadded
640/// base64url characters is a protocol error the receiver must close over; the check is the
641/// session's, because it is about a field value rather than the message's shape.
642#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
643#[serde(rename_all = "snake_case")]
644pub struct GroupUpdate {
645 /// `playing` or `stopped`; a paused group reports `stopped`. An unknown value is preserved.
646 pub playback_state: String,
647 /// 32-byte group identifier as 43 unpadded base64url characters.
648 pub group_id: String,
649 /// Friendly name of the group, plain text of at most 64 bytes in UTF-8.
650 pub group_name: String,
651}
652
653// ---------------------------------------------------------------------------
654// Stream lifecycle
655// ---------------------------------------------------------------------------
656
657/// The `player` object of [`StreamStart`]: the negotiated audio format of a stream.
658#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
659#[serde(rename_all = "snake_case")]
660pub struct StreamStartPlayer {
661 /// Codec of the stream: `opus`, `flac` or `pcm`.
662 pub codec: String,
663 /// Sample rate in hertz.
664 pub sample_rate: u32,
665 /// Number of channels.
666 pub channels: u8,
667 /// Bit depth; ignored for `opus`.
668 pub bit_depth: u8,
669 /// Codec header as standard base64 with padding, for example the `fLaC` marker followed by
670 /// STREAMINFO for FLAC; absent for `pcm` and `opus`.
671 #[serde(default, skip_serializing_if = "Option::is_none")]
672 pub codec_header: Option<String>,
673}
674
675/// `stream/start`: announces a stream and its format.
676///
677/// Sent again with a new format to change the configuration of a running stream.
678#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)]
679#[serde(rename_all = "snake_case")]
680pub struct StreamStart {
681 /// Server clock time in microseconds at which this message was sent.
682 #[serde(default)]
683 pub server_transmitted: i64,
684 /// Player format of the stream; present exactly when the `player` role is active.
685 #[serde(default, skip_serializing_if = "Option::is_none")]
686 pub player: Option<StreamStartPlayer>,
687}
688
689/// `stream/clear`: drops buffered data without ending the stream.
690#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)]
691#[serde(rename_all = "snake_case")]
692pub struct StreamClear {
693 /// Server clock time in microseconds at which this message was sent.
694 #[serde(default)]
695 pub server_transmitted: i64,
696 /// Server clock time from which buffered data is dropped; absent clears everything.
697 #[serde(default, skip_serializing_if = "Option::is_none")]
698 pub from_timestamp: Option<i64>,
699 /// Roles to clear; absent means every active stream.
700 #[serde(default, skip_serializing_if = "Option::is_none")]
701 pub roles: Option<Vec<String>>,
702}
703
704/// `stream/end`: ends one or more streams.
705#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)]
706#[serde(rename_all = "snake_case")]
707pub struct StreamEnd {
708 /// Roles to end; absent means every active stream.
709 #[serde(default, skip_serializing_if = "Option::is_none")]
710 pub roles: Option<Vec<String>>,
711}
712
713// ---------------------------------------------------------------------------
714// Commands
715// ---------------------------------------------------------------------------
716
717/// The `player` object of [`ServerCommand`].
718#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
719#[serde(rename_all = "snake_case")]
720pub struct PlayerCommand {
721 /// Command to run: `volume`, `mute` or `set_output_delay`. A command outside the client's
722 /// advertised set is ignored.
723 pub command: String,
724 /// Target volume in the range 0-100; required for `volume`, absent otherwise.
725 #[serde(default, skip_serializing_if = "Option::is_none")]
726 pub volume: Option<u8>,
727 /// Target mute state; required for `mute`, absent otherwise.
728 #[serde(default, skip_serializing_if = "Option::is_none")]
729 pub mute: Option<bool>,
730 /// Target output delay in milliseconds; required for `set_output_delay`, absent otherwise.
731 #[serde(default, skip_serializing_if = "Option::is_none")]
732 pub output_delay_ms: Option<u32>,
733}
734
735/// `server/command`: a command for one of the client's active roles.
736#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)]
737#[serde(rename_all = "snake_case")]
738pub struct ServerCommand {
739 /// Player command; present exactly when the `player` role is active.
740 #[serde(default, skip_serializing_if = "Option::is_none")]
741 pub player: Option<PlayerCommand>,
742}
743
744/// The `controller` object of [`ClientCommand`].
745///
746/// `command` names the operation and the other fields carry its parameter; a field that does not
747/// belong to the command is absent rather than null.
748#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)]
749#[serde(rename_all = "snake_case")]
750pub struct ControllerCommand {
751 /// Command to run: `play`, `pause`, `stop`, `next`, `previous`, `volume`, `mute`,
752 /// `repeat_off`, `repeat_one`, `repeat_all`, `shuffle`, `unshuffle`, `switch`, `seek` or
753 /// `seek_relative`. A command outside the server's advertised set is ignored by the server.
754 pub command: String,
755 /// Target group volume in the range 0-100; only for `volume`.
756 #[serde(default, skip_serializing_if = "Option::is_none")]
757 pub volume: Option<u8>,
758 /// Target mute state; only for `mute`.
759 #[serde(default, skip_serializing_if = "Option::is_none")]
760 pub mute: Option<bool>,
761 /// Absolute position in milliseconds; only for `seek`.
762 #[serde(default, skip_serializing_if = "Option::is_none")]
763 pub position_ms: Option<u64>,
764 /// Offset from the current position in milliseconds; only for `seek_relative`.
765 #[serde(default, skip_serializing_if = "Option::is_none")]
766 pub offset_ms: Option<i64>,
767}
768
769/// `client/command`: a command the client sends to the server for one of its active roles.
770#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)]
771#[serde(rename_all = "snake_case")]
772pub struct ClientCommand {
773 /// Controller command; present exactly when the `controller` role is active.
774 #[serde(default, skip_serializing_if = "Option::is_none")]
775 pub controller: Option<ControllerCommand>,
776}
777
778// ---------------------------------------------------------------------------
779// Closing
780// ---------------------------------------------------------------------------
781
782/// `client/goodbye`: why the client is closing the connection.
783///
784/// Sent before a graceful close, so the server can tell a restart from a shutdown and whether to
785/// reconnect. `reason` is one of the values `messaging.md` defines; an unknown value is carried
786/// verbatim rather than rejected, so a reason this revision does not name still reaches the peer.
787#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
788#[serde(rename_all = "snake_case")]
789pub struct ClientGoodbye {
790 /// Why the client is leaving, for example `shutdown`, `restart` or `unpaired`.
791 pub reason: String,
792}
793
794// ---------------------------------------------------------------------------
795// Binary audio
796// ---------------------------------------------------------------------------
797
798/// The fixed header of a player audio chunk, the binary message with id [`AUDIO_CHUNK_ID`].
799///
800/// Layout: one message-id byte, an 8-byte big-endian timestamp in microseconds and a 4-byte
801/// big-endian `send_ahead` in microseconds; the encoded audio follows. The timestamp is two's
802/// complement, so negative values round-trip exactly.
803#[derive(Debug, Clone, Copy, PartialEq, Eq)]
804pub struct AudioChunkHeader {
805 /// Server clock time in microseconds at which the first sample of the chunk should be
806 /// output.
807 pub timestamp_us: i64,
808 /// Microseconds between the server transmitting the chunk and [`Self::timestamp_us`].
809 ///
810 /// It measures arrival delay only and never changes when the chunk is played.
811 pub send_ahead: u32,
812}
813
814impl AudioChunkHeader {
815 /// Length of the header, including the message-id byte.
816 pub const LEN: usize = 13;
817
818 /// Parses one audio chunk, returning its header and the encoded audio that follows.
819 ///
820 /// # Errors
821 /// Returns an error for an empty message, for a message whose id is not [`AUDIO_CHUNK_ID`],
822 /// and for a chunk shorter than [`Self::LEN`].
823 pub fn parse(message: &[u8]) -> Result<(Self, &[u8])> {
824 let Some((&id, body)) = message.split_first() else {
825 bail!("empty binary message");
826 };
827 if id != AUDIO_CHUNK_ID {
828 bail!("binary message id {id} is not an audio chunk");
829 }
830 let Some((timestamp, body)) = body.split_at_checked(8) else {
831 bail!("audio chunk truncated: {} bytes", message.len());
832 };
833 let Some((send_ahead, audio)) = body.split_at_checked(4) else {
834 bail!("audio chunk truncated: {} bytes", message.len());
835 };
836 let mut timestamp_us = [0u8; 8];
837 timestamp_us.copy_from_slice(timestamp);
838 let mut send_ahead_us = [0u8; 4];
839 send_ahead_us.copy_from_slice(send_ahead);
840 Ok((
841 Self {
842 timestamp_us: i64::from_be_bytes(timestamp_us),
843 send_ahead: u32::from_be_bytes(send_ahead_us),
844 },
845 audio,
846 ))
847 }
848
849 /// Builds one complete audio chunk from this header and the encoded audio.
850 pub fn encode(&self, audio: &[u8]) -> Vec<u8> {
851 let mut message = Vec::with_capacity(Self::LEN + audio.len());
852 message.push(AUDIO_CHUNK_ID);
853 message.extend_from_slice(&self.timestamp_us.to_be_bytes());
854 message.extend_from_slice(&self.send_ahead.to_be_bytes());
855 message.extend_from_slice(audio);
856 message
857 }
858}
859
860// ---------------------------------------------------------------------------
861// Envelope classification
862// ---------------------------------------------------------------------------
863
864/// One decoded JSON message, classified by its `type` field.
865///
866/// The same type writes the envelope: serializing a variant produces
867/// `{"type": "<group>/<name>", "payload": {..}}`, which is what a session sends.
868///
869/// The enum is non-exhaustive: a newer revision of the protocol defines messages this one does
870/// not, and a receiver must be able to ignore them without a breaking change.
871///
872/// Deserializing this type directly with `serde_json` reports an unknown `type` and a malformed
873/// payload as the same kind of error, so it cannot drive the protocol's rule that the first is
874/// ignored and the second closes the connection. Use [`Incoming::parse`] for received frames,
875/// which tells the two apart.
876#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
877#[serde(tag = "type", content = "payload")]
878#[non_exhaustive]
879pub enum Incoming {
880 /// `client/init`, cleartext.
881 #[serde(rename = "client/init")]
882 ClientInit(ClientInit),
883 /// `server/init`, cleartext.
884 #[serde(rename = "server/init")]
885 ServerInit(ServerInit),
886 /// `server/error`, cleartext, in place of `server/init`.
887 #[serde(rename = "server/error")]
888 ServerError(ServerError),
889 /// `noise/handshake`, cleartext.
890 #[serde(rename = "noise/handshake")]
891 NoiseHandshake(NoiseHandshake),
892 /// `server/hello`.
893 #[serde(rename = "server/hello")]
894 ServerHello(ServerHello),
895 /// `client/hello`.
896 #[serde(rename = "client/hello")]
897 ClientHello(ClientHello),
898 /// `server/activate`.
899 #[serde(rename = "server/activate")]
900 ServerActivate(ServerActivate),
901 /// `client/pair-init`.
902 #[serde(rename = "client/pair-init")]
903 ClientPairInit(ClientPairInit),
904 /// `client/pair-pending`.
905 #[serde(rename = "client/pair-pending")]
906 ClientPairPending(ClientPairPending),
907 /// `server/pair-init`.
908 #[serde(rename = "server/pair-init")]
909 ServerPairInit(ServerPairInit),
910 /// `server/pair-auth`.
911 #[serde(rename = "server/pair-auth")]
912 ServerPairAuth(ServerPairAuth),
913 /// `client/pair-auth`.
914 #[serde(rename = "client/pair-auth")]
915 ClientPairAuth(ClientPairAuth),
916 /// `client/pair-retry`.
917 #[serde(rename = "client/pair-retry")]
918 ClientPairRetry(ClientPairRetry),
919 /// `server/pair-confirm`.
920 #[serde(rename = "server/pair-confirm")]
921 ServerPairConfirm(ServerPairConfirm),
922 /// `client/pair-confirm`.
923 #[serde(rename = "client/pair-confirm")]
924 ClientPairConfirm(ClientPairConfirm),
925 /// `client/pair-finalize`.
926 #[serde(rename = "client/pair-finalize")]
927 ClientPairFinalize(ClientPairFinalize),
928 /// `server/pair-finalize`.
929 #[serde(rename = "server/pair-finalize")]
930 ServerPairFinalize(ServerPairFinalize),
931 /// `server/unpair`.
932 #[serde(rename = "server/unpair")]
933 ServerUnpair(ServerUnpair),
934 /// `client/goodbye`.
935 #[serde(rename = "client/goodbye")]
936 ClientGoodbye(ClientGoodbye),
937 /// `pair/abort`, in both directions.
938 #[serde(rename = "pair/abort")]
939 PairAbort(PairAbort),
940 /// `client/time`.
941 #[serde(rename = "client/time")]
942 ClientTime(ClientTime),
943 /// `server/time`.
944 #[serde(rename = "server/time")]
945 ServerTime(ServerTime),
946 /// `client/state`.
947 #[serde(rename = "client/state")]
948 ClientState(ClientState),
949 /// `server/state`.
950 #[serde(rename = "server/state")]
951 ServerState(ServerState),
952 /// `group/update`.
953 #[serde(rename = "group/update")]
954 GroupUpdate(GroupUpdate),
955 /// `server/command`.
956 #[serde(rename = "server/command")]
957 ServerCommand(ServerCommand),
958 /// `client/command`.
959 #[serde(rename = "client/command")]
960 ClientCommand(ClientCommand),
961 /// `stream/start`.
962 #[serde(rename = "stream/start")]
963 StreamStart(StreamStart),
964 /// `stream/clear`.
965 #[serde(rename = "stream/clear")]
966 StreamClear(StreamClear),
967 /// `stream/end`.
968 #[serde(rename = "stream/end")]
969 StreamEnd(StreamEnd),
970}
971
972impl Incoming {
973 /// Parses one JSON text frame, telling an unknown message type from a malformed message.
974 ///
975 /// `Ok(None)` means the `type` names a message this revision does not implement. The protocol
976 /// requires ignoring such a message, so it is not an error, and returning the identifier would
977 /// only invite callers to treat the normal case as a failure.
978 ///
979 /// `Err(DecodeError::Malformed(..))` means the message cannot be used: either the frame is not
980 /// a JSON object with a string `type`, or the `type` is known and its payload does not parse.
981 /// The protocol treats that as an error, so the caller must act on it.
982 ///
983 /// Deserializing with `serde_json::from_str::<Incoming>` instead reports both cases through the
984 /// same error type; use this method whenever the difference matters.
985 pub fn parse(text: &str) -> Result<Option<Self>, DecodeError> {
986 let envelope: EnvelopeType = serde_json::from_str(text).map_err(DecodeError::Malformed)?;
987 if !is_known_type(&envelope.message_type) {
988 return Ok(None);
989 }
990 serde_json::from_str(text)
991 .map(Some)
992 .map_err(DecodeError::Malformed)
993 }
994}
995
996/// Why a text frame did not produce an [`Incoming`] message.
997#[derive(Debug)]
998pub enum DecodeError {
999 /// The `type` is not one this revision implements.
1000 ///
1001 /// [`Incoming::parse`] reports this case as `Ok(None)` rather than as this variant, because the
1002 /// protocol requires ignoring an unrecognised type instead of closing the connection. The
1003 /// variant stays part of the public error type so a stricter dispatcher can still name the
1004 /// case.
1005 UnknownType(String),
1006 /// The `type` is known, but the message does not deserialize.
1007 Malformed(serde_json::Error),
1008}
1009
1010impl fmt::Display for DecodeError {
1011 fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
1012 match self {
1013 Self::UnknownType(message_type) => {
1014 write!(formatter, "unrecognized message type {message_type:?}")
1015 }
1016 Self::Malformed(error) => write!(formatter, "malformed message: {error}"),
1017 }
1018 }
1019}
1020
1021impl std::error::Error for DecodeError {
1022 fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {
1023 match self {
1024 Self::Malformed(error) => Some(error),
1025 Self::UnknownType(_) => None,
1026 }
1027 }
1028}
1029
1030/// The `type` field of a message envelope, read before the payload is parsed.
1031#[derive(Deserialize)]
1032struct EnvelopeType {
1033 #[serde(rename = "type")]
1034 message_type: String,
1035}
1036
1037/// Message types this revision implements, one per [`Incoming`] variant.
1038///
1039/// A variant added without its entry here would silently read as an unknown type, so the
1040/// integration tests parse one instance of every variant.
1041const KNOWN_TYPES: [&str; 30] = [
1042 "client/init",
1043 "server/init",
1044 "server/error",
1045 "noise/handshake",
1046 "server/hello",
1047 "client/hello",
1048 "server/activate",
1049 "client/pair-init",
1050 "client/pair-pending",
1051 "server/pair-init",
1052 "server/pair-auth",
1053 "client/pair-auth",
1054 "client/pair-retry",
1055 "server/pair-confirm",
1056 "client/pair-confirm",
1057 "client/pair-finalize",
1058 "server/pair-finalize",
1059 "server/unpair",
1060 "client/goodbye",
1061 "pair/abort",
1062 "client/time",
1063 "server/time",
1064 "client/state",
1065 "server/state",
1066 "group/update",
1067 "server/command",
1068 "client/command",
1069 "stream/start",
1070 "stream/clear",
1071 "stream/end",
1072];
1073
1074/// Whether this revision implements a message type.
1075fn is_known_type(message_type: &str) -> bool {
1076 KNOWN_TYPES.contains(&message_type)
1077}