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}
614
615/// `server/state`: the state of each active server role.
616///
617/// A role object that is absent keeps its previous state.
618#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)]
619#[serde(rename_all = "snake_case")]
620pub struct ServerState {
621 /// Metadata state; present exactly when the `metadata` role is active.
622 #[serde(default, skip_serializing_if = "Option::is_none")]
623 pub metadata: Option<Metadata>,
624 /// Controller state; present exactly when the `controller` role is active.
625 #[serde(default, skip_serializing_if = "Option::is_none")]
626 pub controller: Option<ControllerState>,
627}
628
629/// `group/update`: the state and identity of the group this client is part of.
630///
631/// The server sends it after the first `server/activate` and whenever one of the fields changes,
632/// and every message carries all three. `server/state` carries only the role objects, so a client
633/// that wants the group's playback state has no other source. `group_id` that is not 43 unpadded
634/// base64url characters is a protocol error the receiver must close over; the check is the
635/// session's, because it is about a field value rather than the message's shape.
636#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
637#[serde(rename_all = "snake_case")]
638pub struct GroupUpdate {
639 /// `playing` or `stopped`; a paused group reports `stopped`. An unknown value is preserved.
640 pub playback_state: String,
641 /// 32-byte group identifier as 43 unpadded base64url characters.
642 pub group_id: String,
643 /// Friendly name of the group, plain text of at most 64 bytes in UTF-8.
644 pub group_name: String,
645}
646
647// ---------------------------------------------------------------------------
648// Stream lifecycle
649// ---------------------------------------------------------------------------
650
651/// The `player` object of [`StreamStart`]: the negotiated audio format of a stream.
652#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
653#[serde(rename_all = "snake_case")]
654pub struct StreamStartPlayer {
655 /// Codec of the stream: `opus`, `flac` or `pcm`.
656 pub codec: String,
657 /// Sample rate in hertz.
658 pub sample_rate: u32,
659 /// Number of channels.
660 pub channels: u8,
661 /// Bit depth; ignored for `opus`.
662 pub bit_depth: u8,
663 /// Codec header as standard base64 with padding, for example the `fLaC` marker followed by
664 /// STREAMINFO for FLAC; absent for `pcm` and `opus`.
665 #[serde(default, skip_serializing_if = "Option::is_none")]
666 pub codec_header: Option<String>,
667}
668
669/// `stream/start`: announces a stream and its format.
670///
671/// Sent again with a new format to change the configuration of a running stream.
672#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)]
673#[serde(rename_all = "snake_case")]
674pub struct StreamStart {
675 /// Server clock time in microseconds at which this message was sent.
676 #[serde(default)]
677 pub server_transmitted: i64,
678 /// Player format of the stream; present exactly when the `player` role is active.
679 #[serde(default, skip_serializing_if = "Option::is_none")]
680 pub player: Option<StreamStartPlayer>,
681}
682
683/// `stream/clear`: drops buffered data without ending the stream.
684#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)]
685#[serde(rename_all = "snake_case")]
686pub struct StreamClear {
687 /// Server clock time in microseconds at which this message was sent.
688 #[serde(default)]
689 pub server_transmitted: i64,
690 /// Server clock time from which buffered data is dropped; absent clears everything.
691 #[serde(default, skip_serializing_if = "Option::is_none")]
692 pub from_timestamp: Option<i64>,
693 /// Roles to clear; absent means every active stream.
694 #[serde(default, skip_serializing_if = "Option::is_none")]
695 pub roles: Option<Vec<String>>,
696}
697
698/// `stream/end`: ends one or more streams.
699#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)]
700#[serde(rename_all = "snake_case")]
701pub struct StreamEnd {
702 /// Roles to end; absent means every active stream.
703 #[serde(default, skip_serializing_if = "Option::is_none")]
704 pub roles: Option<Vec<String>>,
705}
706
707// ---------------------------------------------------------------------------
708// Commands
709// ---------------------------------------------------------------------------
710
711/// The `player` object of [`ServerCommand`].
712#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
713#[serde(rename_all = "snake_case")]
714pub struct PlayerCommand {
715 /// Command to run: `volume`, `mute` or `set_output_delay`. A command outside the client's
716 /// advertised set is ignored.
717 pub command: String,
718 /// Target volume in the range 0-100; required for `volume`, absent otherwise.
719 #[serde(default, skip_serializing_if = "Option::is_none")]
720 pub volume: Option<u8>,
721 /// Target mute state; required for `mute`, absent otherwise.
722 #[serde(default, skip_serializing_if = "Option::is_none")]
723 pub mute: Option<bool>,
724 /// Target output delay in milliseconds; required for `set_output_delay`, absent otherwise.
725 #[serde(default, skip_serializing_if = "Option::is_none")]
726 pub output_delay_ms: Option<u32>,
727}
728
729/// `server/command`: a command for one of the client's active roles.
730#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)]
731#[serde(rename_all = "snake_case")]
732pub struct ServerCommand {
733 /// Player command; present exactly when the `player` role is active.
734 #[serde(default, skip_serializing_if = "Option::is_none")]
735 pub player: Option<PlayerCommand>,
736}
737
738/// The `controller` object of [`ClientCommand`].
739///
740/// `command` names the operation and the other fields carry its parameter; a field that does not
741/// belong to the command is absent rather than null.
742#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)]
743#[serde(rename_all = "snake_case")]
744pub struct ControllerCommand {
745 /// Command to run: `play`, `pause`, `stop`, `next`, `previous`, `volume`, `mute`,
746 /// `repeat_off`, `repeat_one`, `repeat_all`, `shuffle`, `unshuffle`, `switch`, `seek` or
747 /// `seek_relative`. A command outside the server's advertised set is ignored by the server.
748 pub command: String,
749 /// Target group volume in the range 0-100; only for `volume`.
750 #[serde(default, skip_serializing_if = "Option::is_none")]
751 pub volume: Option<u8>,
752 /// Target mute state; only for `mute`.
753 #[serde(default, skip_serializing_if = "Option::is_none")]
754 pub mute: Option<bool>,
755 /// Absolute position in milliseconds; only for `seek`.
756 #[serde(default, skip_serializing_if = "Option::is_none")]
757 pub position_ms: Option<u64>,
758 /// Offset from the current position in milliseconds; only for `seek_relative`.
759 #[serde(default, skip_serializing_if = "Option::is_none")]
760 pub offset_ms: Option<i64>,
761}
762
763/// `client/command`: a command the client sends to the server for one of its active roles.
764#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)]
765#[serde(rename_all = "snake_case")]
766pub struct ClientCommand {
767 /// Controller command; present exactly when the `controller` role is active.
768 #[serde(default, skip_serializing_if = "Option::is_none")]
769 pub controller: Option<ControllerCommand>,
770}
771
772// ---------------------------------------------------------------------------
773// Closing
774// ---------------------------------------------------------------------------
775
776/// `client/goodbye`: why the client is closing the connection.
777///
778/// Sent before a graceful close, so the server can tell a restart from a shutdown and whether to
779/// reconnect. `reason` is one of the values `messaging.md` defines; an unknown value is carried
780/// verbatim rather than rejected, so a reason this revision does not name still reaches the peer.
781#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
782#[serde(rename_all = "snake_case")]
783pub struct ClientGoodbye {
784 /// Why the client is leaving, for example `shutdown`, `restart` or `unpaired`.
785 pub reason: String,
786}
787
788// ---------------------------------------------------------------------------
789// Binary audio
790// ---------------------------------------------------------------------------
791
792/// The fixed header of a player audio chunk, the binary message with id [`AUDIO_CHUNK_ID`].
793///
794/// Layout: one message-id byte, an 8-byte big-endian timestamp in microseconds and a 4-byte
795/// big-endian `send_ahead` in microseconds; the encoded audio follows. The timestamp is two's
796/// complement, so negative values round-trip exactly.
797#[derive(Debug, Clone, Copy, PartialEq, Eq)]
798pub struct AudioChunkHeader {
799 /// Server clock time in microseconds at which the first sample of the chunk should be
800 /// output.
801 pub timestamp_us: i64,
802 /// Microseconds between the server transmitting the chunk and [`Self::timestamp_us`].
803 ///
804 /// It measures arrival delay only and never changes when the chunk is played.
805 pub send_ahead: u32,
806}
807
808impl AudioChunkHeader {
809 /// Length of the header, including the message-id byte.
810 pub const LEN: usize = 13;
811
812 /// Parses one audio chunk, returning its header and the encoded audio that follows.
813 ///
814 /// # Errors
815 /// Returns an error for an empty message, for a message whose id is not [`AUDIO_CHUNK_ID`],
816 /// and for a chunk shorter than [`Self::LEN`].
817 pub fn parse(message: &[u8]) -> Result<(Self, &[u8])> {
818 let Some((&id, body)) = message.split_first() else {
819 bail!("empty binary message");
820 };
821 if id != AUDIO_CHUNK_ID {
822 bail!("binary message id {id} is not an audio chunk");
823 }
824 let Some((timestamp, body)) = body.split_at_checked(8) else {
825 bail!("audio chunk truncated: {} bytes", message.len());
826 };
827 let Some((send_ahead, audio)) = body.split_at_checked(4) else {
828 bail!("audio chunk truncated: {} bytes", message.len());
829 };
830 let mut timestamp_us = [0u8; 8];
831 timestamp_us.copy_from_slice(timestamp);
832 let mut send_ahead_us = [0u8; 4];
833 send_ahead_us.copy_from_slice(send_ahead);
834 Ok((
835 Self {
836 timestamp_us: i64::from_be_bytes(timestamp_us),
837 send_ahead: u32::from_be_bytes(send_ahead_us),
838 },
839 audio,
840 ))
841 }
842
843 /// Builds one complete audio chunk from this header and the encoded audio.
844 pub fn encode(&self, audio: &[u8]) -> Vec<u8> {
845 let mut message = Vec::with_capacity(Self::LEN + audio.len());
846 message.push(AUDIO_CHUNK_ID);
847 message.extend_from_slice(&self.timestamp_us.to_be_bytes());
848 message.extend_from_slice(&self.send_ahead.to_be_bytes());
849 message.extend_from_slice(audio);
850 message
851 }
852}
853
854// ---------------------------------------------------------------------------
855// Envelope classification
856// ---------------------------------------------------------------------------
857
858/// One decoded JSON message, classified by its `type` field.
859///
860/// The same type writes the envelope: serializing a variant produces
861/// `{"type": "<group>/<name>", "payload": {..}}`, which is what a session sends.
862///
863/// The enum is non-exhaustive: a newer revision of the protocol defines messages this one does
864/// not, and a receiver must be able to ignore them without a breaking change.
865///
866/// Deserializing this type directly with `serde_json` reports an unknown `type` and a malformed
867/// payload as the same kind of error, so it cannot drive the protocol's rule that the first is
868/// ignored and the second closes the connection. Use [`Incoming::parse`] for received frames,
869/// which tells the two apart.
870#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
871#[serde(tag = "type", content = "payload")]
872#[non_exhaustive]
873pub enum Incoming {
874 /// `client/init`, cleartext.
875 #[serde(rename = "client/init")]
876 ClientInit(ClientInit),
877 /// `server/init`, cleartext.
878 #[serde(rename = "server/init")]
879 ServerInit(ServerInit),
880 /// `server/error`, cleartext, in place of `server/init`.
881 #[serde(rename = "server/error")]
882 ServerError(ServerError),
883 /// `noise/handshake`, cleartext.
884 #[serde(rename = "noise/handshake")]
885 NoiseHandshake(NoiseHandshake),
886 /// `server/hello`.
887 #[serde(rename = "server/hello")]
888 ServerHello(ServerHello),
889 /// `client/hello`.
890 #[serde(rename = "client/hello")]
891 ClientHello(ClientHello),
892 /// `server/activate`.
893 #[serde(rename = "server/activate")]
894 ServerActivate(ServerActivate),
895 /// `client/pair-init`.
896 #[serde(rename = "client/pair-init")]
897 ClientPairInit(ClientPairInit),
898 /// `client/pair-pending`.
899 #[serde(rename = "client/pair-pending")]
900 ClientPairPending(ClientPairPending),
901 /// `server/pair-init`.
902 #[serde(rename = "server/pair-init")]
903 ServerPairInit(ServerPairInit),
904 /// `server/pair-auth`.
905 #[serde(rename = "server/pair-auth")]
906 ServerPairAuth(ServerPairAuth),
907 /// `client/pair-auth`.
908 #[serde(rename = "client/pair-auth")]
909 ClientPairAuth(ClientPairAuth),
910 /// `client/pair-retry`.
911 #[serde(rename = "client/pair-retry")]
912 ClientPairRetry(ClientPairRetry),
913 /// `server/pair-confirm`.
914 #[serde(rename = "server/pair-confirm")]
915 ServerPairConfirm(ServerPairConfirm),
916 /// `client/pair-confirm`.
917 #[serde(rename = "client/pair-confirm")]
918 ClientPairConfirm(ClientPairConfirm),
919 /// `client/pair-finalize`.
920 #[serde(rename = "client/pair-finalize")]
921 ClientPairFinalize(ClientPairFinalize),
922 /// `server/pair-finalize`.
923 #[serde(rename = "server/pair-finalize")]
924 ServerPairFinalize(ServerPairFinalize),
925 /// `server/unpair`.
926 #[serde(rename = "server/unpair")]
927 ServerUnpair(ServerUnpair),
928 /// `client/goodbye`.
929 #[serde(rename = "client/goodbye")]
930 ClientGoodbye(ClientGoodbye),
931 /// `pair/abort`, in both directions.
932 #[serde(rename = "pair/abort")]
933 PairAbort(PairAbort),
934 /// `client/time`.
935 #[serde(rename = "client/time")]
936 ClientTime(ClientTime),
937 /// `server/time`.
938 #[serde(rename = "server/time")]
939 ServerTime(ServerTime),
940 /// `client/state`.
941 #[serde(rename = "client/state")]
942 ClientState(ClientState),
943 /// `server/state`.
944 #[serde(rename = "server/state")]
945 ServerState(ServerState),
946 /// `group/update`.
947 #[serde(rename = "group/update")]
948 GroupUpdate(GroupUpdate),
949 /// `server/command`.
950 #[serde(rename = "server/command")]
951 ServerCommand(ServerCommand),
952 /// `client/command`.
953 #[serde(rename = "client/command")]
954 ClientCommand(ClientCommand),
955 /// `stream/start`.
956 #[serde(rename = "stream/start")]
957 StreamStart(StreamStart),
958 /// `stream/clear`.
959 #[serde(rename = "stream/clear")]
960 StreamClear(StreamClear),
961 /// `stream/end`.
962 #[serde(rename = "stream/end")]
963 StreamEnd(StreamEnd),
964}
965
966impl Incoming {
967 /// Parses one JSON text frame, telling an unknown message type from a malformed message.
968 ///
969 /// `Ok(None)` means the `type` names a message this revision does not implement. The protocol
970 /// requires ignoring such a message, so it is not an error, and returning the identifier would
971 /// only invite callers to treat the normal case as a failure.
972 ///
973 /// `Err(DecodeError::Malformed(..))` means the message cannot be used: either the frame is not
974 /// a JSON object with a string `type`, or the `type` is known and its payload does not parse.
975 /// The protocol treats that as an error, so the caller must act on it.
976 ///
977 /// Deserializing with `serde_json::from_str::<Incoming>` instead reports both cases through the
978 /// same error type; use this method whenever the difference matters.
979 pub fn parse(text: &str) -> Result<Option<Self>, DecodeError> {
980 let envelope: EnvelopeType = serde_json::from_str(text).map_err(DecodeError::Malformed)?;
981 if !is_known_type(&envelope.message_type) {
982 return Ok(None);
983 }
984 serde_json::from_str(text)
985 .map(Some)
986 .map_err(DecodeError::Malformed)
987 }
988}
989
990/// Why a text frame did not produce an [`Incoming`] message.
991#[derive(Debug)]
992pub enum DecodeError {
993 /// The `type` is not one this revision implements.
994 ///
995 /// [`Incoming::parse`] reports this case as `Ok(None)` rather than as this variant, because the
996 /// protocol requires ignoring an unrecognised type instead of closing the connection. The
997 /// variant stays part of the public error type so a stricter dispatcher can still name the
998 /// case.
999 UnknownType(String),
1000 /// The `type` is known, but the message does not deserialize.
1001 Malformed(serde_json::Error),
1002}
1003
1004impl fmt::Display for DecodeError {
1005 fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
1006 match self {
1007 Self::UnknownType(message_type) => {
1008 write!(formatter, "unrecognized message type {message_type:?}")
1009 }
1010 Self::Malformed(error) => write!(formatter, "malformed message: {error}"),
1011 }
1012 }
1013}
1014
1015impl std::error::Error for DecodeError {
1016 fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {
1017 match self {
1018 Self::Malformed(error) => Some(error),
1019 Self::UnknownType(_) => None,
1020 }
1021 }
1022}
1023
1024/// The `type` field of a message envelope, read before the payload is parsed.
1025#[derive(Deserialize)]
1026struct EnvelopeType {
1027 #[serde(rename = "type")]
1028 message_type: String,
1029}
1030
1031/// Message types this revision implements, one per [`Incoming`] variant.
1032///
1033/// A variant added without its entry here would silently read as an unknown type, so the
1034/// integration tests parse one instance of every variant.
1035const KNOWN_TYPES: [&str; 30] = [
1036 "client/init",
1037 "server/init",
1038 "server/error",
1039 "noise/handshake",
1040 "server/hello",
1041 "client/hello",
1042 "server/activate",
1043 "client/pair-init",
1044 "client/pair-pending",
1045 "server/pair-init",
1046 "server/pair-auth",
1047 "client/pair-auth",
1048 "client/pair-retry",
1049 "server/pair-confirm",
1050 "client/pair-confirm",
1051 "client/pair-finalize",
1052 "server/pair-finalize",
1053 "server/unpair",
1054 "client/goodbye",
1055 "pair/abort",
1056 "client/time",
1057 "server/time",
1058 "client/state",
1059 "server/state",
1060 "group/update",
1061 "server/command",
1062 "client/command",
1063 "stream/start",
1064 "stream/clear",
1065 "stream/end",
1066];
1067
1068/// Whether this revision implements a message type.
1069fn is_known_type(message_type: &str) -> bool {
1070 KNOWN_TYPES.contains(&message_type)
1071}