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`] for every audio chunk, and a discard or a flush at each boundary listed on
11//! [`Sink::discard_from`] and [`Sink::flush`]. A sink may block only as long as it takes to
12//! enqueue the frame: a write that never returns stalls the connection, because the trait is
13//! synchronous and the client has no second thread to read the socket.
14//!
15//! An error from [`Sink::open`], [`Sink::write`], [`Sink::discard_from`] or [`Sink::flush`] is
16//! fatal for the connection: the client reports it and stops instead of retrying a broken output,
17//! so the host has to build a new sink and call [`connect`](crate::connect) again.
18
19use std::fmt;
20use std::time::Duration;
21
22/// One audio frame handed to a [`Sink`].
23#[derive(Debug, Clone, PartialEq, Eq)]
24pub enum AudioFrame<'a> {
25 /// Raw PCM samples in the layout announced by [`AudioFormat`].
26 Pcm(&'a [u8]),
27 /// One encoded frame, to be decoded or passed to an audio pipeline unchanged.
28 Encoded {
29 /// Codec the frame is encoded with.
30 codec: Codec,
31 /// Encoded bytes, one frame of the codec's stream.
32 data: &'a [u8],
33 },
34}
35
36/// Audio codec of a stream.
37///
38/// The protocol names three codecs; [`Codec::Other`] preserves one this revision does not know, so
39/// a passthrough sink can still forward it. A sink that decodes must reject the values it cannot
40/// handle instead of guessing.
41#[derive(Debug, Clone, PartialEq, Eq)]
42pub enum Codec {
43 /// Raw samples, layout given by [`AudioFormat`].
44 Pcm,
45 /// FLAC.
46 Flac,
47 /// Opus.
48 Opus,
49 /// A codec identifier this revision does not name, unchanged from the wire.
50 Other(String),
51}
52
53impl Codec {
54 /// Returns the identifier as it appears on the wire.
55 #[must_use]
56 pub fn as_str(&self) -> &str {
57 match self {
58 Self::Pcm => "pcm",
59 Self::Flac => "flac",
60 Self::Opus => "opus",
61 Self::Other(name) => name,
62 }
63 }
64}
65
66impl fmt::Display for Codec {
67 fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
68 formatter.write_str(self.as_str())
69 }
70}
71
72impl From<&str> for Codec {
73 fn from(value: &str) -> Self {
74 match value {
75 "pcm" => Self::Pcm,
76 "flac" => Self::Flac,
77 "opus" => Self::Opus,
78 other => Self::Other(other.to_owned()),
79 }
80 }
81}
82
83impl From<String> for Codec {
84 fn from(value: String) -> Self {
85 match value.as_str() {
86 "pcm" => Self::Pcm,
87 "flac" => Self::Flac,
88 "opus" => Self::Opus,
89 _ => Self::Other(value),
90 }
91 }
92}
93
94/// The audio format a stream announces.
95///
96/// The fields are the wire values of the stream announcement, unchanged. For [`Codec::Pcm`] the
97/// samples are signed 16-bit little-endian when `bit_depth` is 16, interleaved by channel; other
98/// depths keep the same convention scaled to the announced width.
99///
100/// The struct is non-exhaustive so a later protocol revision can add a field without breaking a
101/// sink implementation. A sink only receives it from [`Sink::open`].
102#[derive(Debug, Clone, PartialEq, Eq)]
103#[non_exhaustive]
104pub struct AudioFormat {
105 /// Codec of the stream.
106 pub codec: Codec,
107 /// Sample rate in hertz.
108 pub sample_rate: u32,
109 /// Number of interleaved channels.
110 pub channels: u8,
111 /// Bits per sample; meaningful for [`Codec::Pcm`] and [`Codec::Flac`].
112 pub bit_depth: u8,
113 /// Codec header carried by the stream announcement, decoded from its base64 form.
114 ///
115 /// For FLAC this is the `fLaC` marker followed by `STREAMINFO`; a decoder needs it before the
116 /// first frame. Absent for PCM and Opus. The bytes are exactly what the server sent.
117 pub codec_header: Option<Vec<u8>>,
118}
119
120/// Audio output owned by the host application.
121///
122/// A sink is moved into the connection and reused across reconnects, so its output device may stay
123/// open for the whole lifetime of the connection rather than per session. Dropping it must stop
124/// playback: the client drops the sink when the connection ends.
125pub trait Sink: Send + 'static {
126 /// Prepares the output for `format`.
127 ///
128 /// The client calls this once per announced stream, after flushing the previous one, and
129 /// before it hands over the first chunk. The same sink sees the streams of every connection
130 /// attempt, and a new attempt announces its own format, so an implementation must not assume
131 /// that the format it last saw is still current. A format the sink cannot play is an error,
132 /// which ends the connection: the client does not retry a sink that failed.
133 fn open(&mut self, format: AudioFormat) -> anyhow::Result<()>;
134
135 /// Writes one frame.
136 ///
137 /// `due` is the local instant at which the first sample of the frame should reach the
138 /// speakers. It is a playout deadline, not a wake-up call: a sink that buffers ahead compares
139 /// it with its own clock, and a deadline that is already past means "play as soon as
140 /// possible". The client reports [`std::time::Instant::now`] while its clock estimate is not
141 /// ready, so the deadline carries no guarantee in that state.
142 ///
143 /// An error ends the connection: the host cannot recover a broken output from here, and the
144 /// client does not retry a sink that failed.
145 fn write(&mut self, frame: AudioFrame<'_>, due: std::time::Instant) -> anyhow::Result<()>;
146
147 /// Drops audio that is buffered but not audible yet.
148 ///
149 /// Called:
150 ///
151 /// - on `stream/start`, after the previous stream and before [`Sink::open`] for the new one,
152 /// - on `stream/end`, after [`Event::StreamEnd`](crate::Event::StreamEnd),
153 /// - on a `stream/clear` that carries no timestamp, after
154 /// [`Event::StreamClear`](crate::Event::StreamClear); a clear that carries one is a
155 /// [`Sink::discard_from`] instead,
156 /// - when the server removes the `player@v1` role, after an
157 /// [`Event::StreamEnd`](crate::Event::StreamEnd) with
158 /// [`StreamEndReason::RoleRemoved`](crate::StreamEndReason::RoleRemoved), and
159 /// - after a connection attempt ends, before the client reconnects, so audio buffered for the
160 /// session that ended cannot become audible on the next one.
161 ///
162 /// It must succeed when no stream is open, so a sink can treat it as "discard everything, keep
163 /// the output device". An error ends the connection.
164 fn flush(&mut self) -> anyhow::Result<()>;
165
166 /// Drops the buffered audio that is due at or after `due`, keeping what plays earlier.
167 ///
168 /// Called on a `stream/clear` that carries a `from_timestamp`, after
169 /// [`Event::StreamClear`](crate::Event::StreamClear). `due` is the server timestamp mapped
170 /// through the client's clock estimate. It is [`std::time::Instant::now`] while no estimate is
171 /// ready, for a timestamp that already lies in the past, and when the mapping would overflow —
172 /// each of which drops everything buffered and matches [`Sink::flush`].
173 ///
174 /// It must succeed when no stream is open or no queue exists: an empty queue discards nothing.
175 /// A clear can arrive before `stream/start` or after `stream/end`, and the client does not
176 /// withhold it.
177 ///
178 /// The default drops everything, so a sink with no timestamped queue keeps the flush
179 /// behaviour without implementing this. An error ends the connection.
180 fn discard_from(&mut self, due: std::time::Instant) -> anyhow::Result<()> {
181 let _ = due;
182 self.flush()
183 }
184
185 /// Reports the delay the output adds **after** the audio port: external speakers, amplifiers, a
186 /// chain after the DAC. Decoder, pipeline and device-internal buffer latency belong in the host's
187 /// playout scheduling, not here. A conformant server factors this value into its send-ahead, so
188 /// reporting a buffer here raises the lead instead of compensating it; the server in this
189 /// workspace ignores the reported timing until `docs/spec-deviations.md` #17 closes.
190 ///
191 /// The host restores the same value across restarts and reconnections: the protocol requires
192 /// `output_delay_ms` to persist, and this trait is the only place the client learns it.
193 ///
194 /// `None` means the sink does not know, which the client treats as no additional delay.
195 fn output_delay(&self) -> Option<Duration> {
196 None
197 }
198
199 /// Reports how many times the output ran empty since it was opened.
200 ///
201 /// This is diagnostic only; the client never changes its behaviour because of it.
202 fn underruns(&self) -> u64 {
203 0
204 }
205}
206
207#[cfg(test)]
208mod tests {
209 use std::sync::atomic::{AtomicUsize, Ordering};
210 use std::sync::Arc;
211
212 use super::*;
213
214 /// A sink that implements only the required methods and counts its flushes.
215 struct FlushingSink {
216 flushes: Arc<AtomicUsize>,
217 }
218
219 impl Sink for FlushingSink {
220 fn open(&mut self, _format: AudioFormat) -> anyhow::Result<()> {
221 Ok(())
222 }
223
224 fn write(
225 &mut self,
226 _frame: AudioFrame<'_>,
227 _due: std::time::Instant,
228 ) -> anyhow::Result<()> {
229 Ok(())
230 }
231
232 fn flush(&mut self) -> anyhow::Result<()> {
233 self.flushes.fetch_add(1, Ordering::SeqCst);
234 Ok(())
235 }
236 }
237
238 #[test]
239 fn a_sink_without_its_own_discard_flushes_everything() {
240 let flushes = Arc::new(AtomicUsize::new(0));
241 let mut sink = FlushingSink {
242 flushes: Arc::clone(&flushes),
243 };
244 sink.discard_from(std::time::Instant::now())
245 .expect("the default discard must flush");
246 assert_eq!(
247 flushes.load(Ordering::SeqCst),
248 1,
249 "a sink without its own discard must receive one flush"
250 );
251 }
252
253 #[test]
254 fn codec_names_roundtrip_through_the_wire_identifier() {
255 for (name, codec) in [
256 ("pcm", Codec::Pcm),
257 ("flac", Codec::Flac),
258 ("opus", Codec::Opus),
259 ("future", Codec::Other("future".to_owned())),
260 ] {
261 assert_eq!(Codec::from(name), codec);
262 assert_eq!(codec.as_str(), name);
263 assert_eq!(codec.to_string(), name);
264 assert_eq!(Codec::from(name.to_owned()), codec);
265 }
266 }
267}