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