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`] for every audio chunk, and a flush at each boundary listed on
11//! [`Sink::flush`]. A sink may block only as long as it takes to enqueue the frame: a write that
12//! never returns stalls the connection, because the trait is synchronous and the client has no
13//! second thread to read the socket.
14//!
15//! An error from [`Sink::open`], [`Sink::write`] or [`Sink::flush`] is fatal for the connection:
16//! the client reports it and stops instead of retrying a broken output, so the host has to build a
17//! 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 `stream/clear`, which seeks or restarts the stream without ending it, after
154    ///   [`Event::StreamClear`](crate::Event::StreamClear),
155    /// - when the server removes the `player@v1` role, after an
156    ///   [`Event::StreamEnd`](crate::Event::StreamEnd) with
157    ///   [`StreamEndReason::RoleRemoved`](crate::StreamEndReason::RoleRemoved), and
158    /// - after a connection attempt ends, before the client reconnects, so audio buffered for the
159    ///   session that ended cannot become audible on the next one.
160    ///
161    /// It must succeed when no stream is open, so a sink can treat it as "discard everything, keep
162    /// the output device". An error ends the connection.
163    fn flush(&mut self) -> anyhow::Result<()>;
164
165    /// Reports the output delay the sink adds beyond the audio port.
166    ///
167    /// The client uses it when it reports its timing to the server. `None` means the sink does not
168    /// know, which the client treats as no additional delay.
169    fn latency(&self) -> Option<Duration> {
170        None
171    }
172
173    /// Reports how many times the output ran empty since it was opened.
174    ///
175    /// This is diagnostic only; the client never changes its behaviour because of it.
176    fn underruns(&self) -> u64 {
177        0
178    }
179}
180
181#[cfg(test)]
182mod tests {
183    use super::*;
184
185    #[test]
186    fn codec_names_roundtrip_through_the_wire_identifier() {
187        for (name, codec) in [
188            ("pcm", Codec::Pcm),
189            ("flac", Codec::Flac),
190            ("opus", Codec::Opus),
191            ("future", Codec::Other("future".to_owned())),
192        ] {
193            assert_eq!(Codec::from(name), codec);
194            assert_eq!(codec.as_str(), name);
195            assert_eq!(codec.to_string(), name);
196            assert_eq!(Codec::from(name.to_owned()), codec);
197        }
198    }
199}