Skip to main content

syncspin_client/
sink.rs

1//! Audio output abstraction.
2//!
3//! The client owns the connection and the clock; the host owns the speakers. Everything that
4//! touches an audio device sits behind [`Sink`], which keeps this crate free of platform
5//! dependencies and lets a test record the frames instead of playing them.
6//!
7//! A sink is moved into [`connect`](crate::connect) once and reused for every connection attempt
8//! the client makes, so a reconnect does not need the host to build another one. Calls are strictly
9//! ordered and come from the client's task: a flush and then [`Sink::open`] when a stream starts,
10//! [`Sink::write`] when a frame is due, and a discard or a flush at each boundary listed on
11//! [`Sink::discard_from`] and [`Sink::flush`]. The client owns the playout clock: it schedules each
12//! frame from its server timestamp and calls [`Sink::write`] when the frame's pre-port write time
13//! has arrived, so a sink writes on call instead of scheduling again. A sink may block only as long
14//! as it takes to enqueue the frame: a write that never returns stalls the connection, because the
15//! trait is synchronous and the client has no second thread to read the socket.
16//!
17//! An error from [`Sink::open`], [`Sink::write`], [`Sink::discard_from`] or [`Sink::flush`] is
18//! fatal for the connection: the client reports it and stops instead of retrying a broken output,
19//! so the host has to build a new sink and call [`connect`](crate::connect) again.
20
21use std::fmt;
22use std::time::Duration;
23
24/// One audio frame handed to a [`Sink`].
25#[derive(Debug, Clone, PartialEq, Eq)]
26pub enum AudioFrame<'a> {
27    /// Raw PCM samples in the layout announced by [`AudioFormat`].
28    Pcm(&'a [u8]),
29    /// One encoded frame, to be decoded or passed to an audio pipeline unchanged.
30    Encoded {
31        /// Codec the frame is encoded with.
32        codec: Codec,
33        /// Encoded bytes, one frame of the codec's stream.
34        data: &'a [u8],
35    },
36}
37
38/// Audio codec of a stream.
39///
40/// The protocol names three codecs; [`Codec::Other`] preserves one this revision does not know, so
41/// a passthrough sink can still forward it. A sink that decodes must reject the values it cannot
42/// handle instead of guessing.
43#[derive(Debug, Clone, PartialEq, Eq)]
44pub enum Codec {
45    /// Raw samples, layout given by [`AudioFormat`].
46    Pcm,
47    /// FLAC.
48    Flac,
49    /// Opus.
50    Opus,
51    /// A codec identifier this revision does not name, unchanged from the wire.
52    Other(String),
53}
54
55impl Codec {
56    /// Returns the identifier as it appears on the wire.
57    #[must_use]
58    pub fn as_str(&self) -> &str {
59        match self {
60            Self::Pcm => "pcm",
61            Self::Flac => "flac",
62            Self::Opus => "opus",
63            Self::Other(name) => name,
64        }
65    }
66}
67
68impl fmt::Display for Codec {
69    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
70        formatter.write_str(self.as_str())
71    }
72}
73
74impl From<&str> for Codec {
75    fn from(value: &str) -> Self {
76        match value {
77            "pcm" => Self::Pcm,
78            "flac" => Self::Flac,
79            "opus" => Self::Opus,
80            other => Self::Other(other.to_owned()),
81        }
82    }
83}
84
85impl From<String> for Codec {
86    fn from(value: String) -> Self {
87        match value.as_str() {
88            "pcm" => Self::Pcm,
89            "flac" => Self::Flac,
90            "opus" => Self::Opus,
91            _ => Self::Other(value),
92        }
93    }
94}
95
96/// The audio format a stream announces.
97///
98/// The fields are the wire values of the stream announcement, unchanged. For [`Codec::Pcm`] the
99/// samples are signed 16-bit little-endian when `bit_depth` is 16, interleaved by channel; other
100/// depths keep the same convention scaled to the announced width.
101///
102/// The struct is non-exhaustive so a later protocol revision can add a field without breaking a
103/// sink implementation. A sink only receives it from [`Sink::open`].
104#[derive(Debug, Clone, PartialEq, Eq)]
105#[non_exhaustive]
106pub struct AudioFormat {
107    /// Codec of the stream.
108    pub codec: Codec,
109    /// Sample rate in hertz.
110    pub sample_rate: u32,
111    /// Number of interleaved channels.
112    pub channels: u8,
113    /// Bits per sample; meaningful for [`Codec::Pcm`] and [`Codec::Flac`].
114    pub bit_depth: u8,
115    /// Codec header carried by the stream announcement, decoded from its base64 form.
116    ///
117    /// For FLAC this is the `fLaC` marker followed by `STREAMINFO`; a decoder needs it before the
118    /// first frame. Absent for PCM and Opus. The bytes are exactly what the server sent.
119    pub codec_header: Option<Vec<u8>>,
120}
121
122impl AudioFormat {
123    /// Builds a PCM format.
124    ///
125    /// Samples are interleaved by channel and encoded as signed little-endian integers of
126    /// `bit_depth` bits, which is what the specification's PCM convention describes; 24-bit samples
127    /// are packed as three bytes.
128    ///
129    /// The values are not validated. A server must support PCM at 16 bit, one or two channels and
130    /// 44.1 or 48 kHz, and may support others, so a format outside that is for the host to judge: a
131    /// zero channel count or a bit depth that is not a whole number of bytes describes no stream.
132    pub fn pcm(sample_rate: u32, channels: u8, bit_depth: u8) -> AudioFormat {
133        AudioFormat {
134            codec: Codec::Pcm,
135            sample_rate,
136            channels,
137            bit_depth,
138            codec_header: None,
139        }
140    }
141}
142
143/// Audio output owned by the host application.
144///
145/// A sink is moved into the connection and reused across reconnects, so its output device may stay
146/// open for the whole lifetime of the connection rather than per session. Dropping it must stop
147/// playback: the client drops the sink when the connection ends.
148pub trait Sink: Send + 'static {
149    /// Prepares the output for `format`.
150    ///
151    /// The client calls this once per announced stream, after flushing the previous one, and
152    /// before it hands over the first chunk. The same sink sees the streams of every connection
153    /// attempt, and a new attempt announces its own format, so an implementation must not assume
154    /// that the format it last saw is still current. A format the sink cannot play is an error,
155    /// which ends the connection: the client does not retry a sink that failed.
156    fn open(&mut self, format: AudioFormat) -> anyhow::Result<()>;
157
158    /// Writes one frame.
159    ///
160    /// The client schedules playout and calls this at the frame's wake time, so the sink writes it
161    /// now and must not schedule it again - otherwise a frame whose sink buffers internally is
162    /// delayed twice. The call is already early enough to fill the sink's
163    /// [`Sink::pre_port_delay`].
164    ///
165    /// `due` is the local instant at which the first sample of the frame should reach the audio
166    /// port, with the sink's [`Sink::output_delay`] already subtracted. The sink's pre-port delay
167    /// is compensated by the instant of this call, not by this value. `due` is informational: a
168    /// sink that forwards the frame to its pipeline ignores it, one that buffers ahead may compare
169    /// it with its own clock, and a deadline that is already past means "write as soon as
170    /// possible". The client reports [`std::time::Instant::now`] while its clock estimate is not
171    /// ready, so the value carries no guarantee in that state.
172    ///
173    /// An error ends the connection: the host cannot recover a broken output from here, and the
174    /// client does not retry a sink that failed.
175    fn write(&mut self, frame: AudioFrame<'_>, due: std::time::Instant) -> anyhow::Result<()>;
176
177    /// Drops audio that is buffered but not audible yet.
178    ///
179    /// Called:
180    ///
181    /// - on `stream/start`, after the previous stream and before [`Sink::open`] for the new one,
182    /// - on `stream/end`, after [`Event::StreamEnd`](crate::Event::StreamEnd),
183    /// - on a `stream/clear` that carries no timestamp, after
184    ///   [`Event::StreamClear`](crate::Event::StreamClear); a clear that carries one is a
185    ///   [`Sink::discard_from`] instead,
186    /// - when the server removes the `player@v1` role, after an
187    ///   [`Event::StreamEnd`](crate::Event::StreamEnd) with
188    ///   [`StreamEndReason::RoleRemoved`](crate::StreamEndReason::RoleRemoved), and
189    /// - after a connection attempt ends, before the client reconnects, so audio buffered for the
190    ///   session that ended cannot become audible on the next one.
191    ///
192    /// It must succeed when no stream is open, so a sink can treat it as "discard everything, keep
193    /// the output device". An error ends the connection.
194    fn flush(&mut self) -> anyhow::Result<()>;
195
196    /// Drops the buffered audio that is due at or after `due`, keeping what plays earlier.
197    ///
198    /// Called on a `stream/clear` that carries a `from_timestamp`, after
199    /// [`Event::StreamClear`](crate::Event::StreamClear). The client already dropped its own queued
200    /// frames at or after that server timestamp; this call is for the audio the sink holds itself.
201    /// `due` is the server timestamp mapped through the client's clock estimate, with the sink's
202    /// [`Sink::output_delay`] subtracted: the local deadline the sink would have been given for that
203    /// server time. It is [`std::time::Instant::now`] while no estimate is ready, for a timestamp
204    /// that already lies in the past, and when the mapping would overflow — each of which drops
205    /// everything buffered and matches [`Sink::flush`].
206    ///
207    /// It must succeed when no stream is open or no queue exists: an empty queue discards nothing.
208    /// A clear can arrive before `stream/start` or after `stream/end`, and the client does not
209    /// withhold it.
210    ///
211    /// The default drops everything, so a sink with no timestamped queue keeps the flush
212    /// behaviour without implementing this. An error ends the connection.
213    fn discard_from(&mut self, due: std::time::Instant) -> anyhow::Result<()> {
214        let _ = due;
215        self.flush()
216    }
217
218    /// Reports the delay between [`Sink::write`] and the audio port: decoder, pipeline, driver and
219    /// device buffers inside the sink. Not the post-port delay reported to the server; that is
220    /// [`Sink::output_delay`].
221    ///
222    /// The client calls [`Sink::write`] this much before the frame's playout deadline, so the frame
223    /// reaches the port at `due`. A sink that forwards frames straight to its pipeline leaves this
224    /// at zero; one whose output buffers internally reports the buffer here so the client can fill
225    /// it. A value that belongs on the post-port side raises the lead the server sends ahead
226    /// instead of compensating it, because the server factors `output_delay` into that lead.
227    ///
228    /// The client polls this when a stream opens, after every `client/state` report, after every
229    /// clock burst, once about half a second after an accepted `set_output_delay`, and when the host
230    /// calls `ControlHandle::output_delay_applied`; a change moves the timer, and because the
231    /// reported lead is at least the pre-port delay, a change that moves that lead in either
232    /// direction sends an updated `required_lead_time_ms`. The default is zero.
233    fn pre_port_delay(&self) -> Duration {
234        Duration::ZERO
235    }
236
237    /// Reports the delay the output adds **after** the audio port: external speakers, amplifiers, a
238    /// chain after the DAC. Decoder, pipeline and device-internal buffer latency belong in the host's
239    /// playout scheduling, not here. A conformant server factors this value into its send-ahead, so
240    /// reporting a buffer here raises the lead instead of compensating it; the server in this
241    /// workspace ignores the reported timing until `docs/spec-deviations.md` #17 closes.
242    ///
243    /// The host restores the same value across restarts and reconnections: the protocol requires
244    /// `output_delay_ms` to persist, and this trait is the only place the client learns it. The
245    /// client polls it at the same points as [`Sink::pre_port_delay`] (stream open, after every
246    /// `client/state` report, after every clock burst, the fallback read after `set_output_delay`
247    /// and `ControlHandle::output_delay_applied`); a change re-maps the queued
248    /// deadlines and sends a new `client/state`, because `output_delay_ms` is a player field.
249    ///
250    /// `None` means the sink does not know, which the client treats as no additional delay.
251    fn output_delay(&self) -> Option<Duration> {
252        None
253    }
254
255    /// Reports how many times the output ran empty since it was opened.
256    ///
257    /// This is diagnostic only; the client never changes its behaviour because of it.
258    fn underruns(&self) -> u64 {
259        0
260    }
261}
262
263#[cfg(test)]
264mod tests {
265    use std::sync::atomic::{AtomicUsize, Ordering};
266    use std::sync::Arc;
267
268    use super::*;
269
270    /// A sink that implements only the required methods and counts its flushes.
271    struct FlushingSink {
272        flushes: Arc<AtomicUsize>,
273    }
274
275    impl Sink for FlushingSink {
276        fn open(&mut self, _format: AudioFormat) -> anyhow::Result<()> {
277            Ok(())
278        }
279
280        fn write(
281            &mut self,
282            _frame: AudioFrame<'_>,
283            _due: std::time::Instant,
284        ) -> anyhow::Result<()> {
285            Ok(())
286        }
287
288        fn flush(&mut self) -> anyhow::Result<()> {
289            self.flushes.fetch_add(1, Ordering::SeqCst);
290            Ok(())
291        }
292    }
293
294    #[test]
295    fn a_sink_without_its_own_discard_flushes_everything() {
296        let flushes = Arc::new(AtomicUsize::new(0));
297        let mut sink = FlushingSink {
298            flushes: Arc::clone(&flushes),
299        };
300        sink.discard_from(std::time::Instant::now())
301            .expect("the default discard must flush");
302        assert_eq!(
303            flushes.load(Ordering::SeqCst),
304            1,
305            "a sink without its own discard must receive one flush"
306        );
307    }
308
309    #[test]
310    fn codec_names_roundtrip_through_the_wire_identifier() {
311        for (name, codec) in [
312            ("pcm", Codec::Pcm),
313            ("flac", Codec::Flac),
314            ("opus", Codec::Opus),
315            ("future", Codec::Other("future".to_owned())),
316        ] {
317            assert_eq!(Codec::from(name), codec);
318            assert_eq!(codec.as_str(), name);
319            assert_eq!(codec.to_string(), name);
320            assert_eq!(Codec::from(name.to_owned()), codec);
321        }
322    }
323
324    #[test]
325    fn a_pcm_format_carries_its_parameters() {
326        let format = AudioFormat::pcm(48_000, 2, 16);
327        assert_eq!(format.codec, Codec::Pcm);
328        assert_eq!(format.sample_rate, 48_000);
329        assert_eq!(format.channels, 2);
330        assert_eq!(format.bit_depth, 16);
331        assert!(format.codec_header.is_none(), "PCM carries no codec header");
332    }
333}