Skip to main content

weirdnet_streaming/
types.rs

1//! The data a stream carries.
2use serde::{Deserialize, Serialize};
3use std::fmt;
4
5/// A stream's id, unique within its publisher's hub.
6#[derive(Clone, Debug, PartialEq, Eq, Hash, PartialOrd, Ord, Serialize, Deserialize)]
7pub struct StreamId(String);
8
9impl StreamId {
10    /// An id from text.
11    pub fn new(s: &str) -> Self {
12        StreamId(s.to_string())
13    }
14    /// The text.
15    pub fn as_str(&self) -> &str {
16        &self.0
17    }
18}
19
20impl fmt::Display for StreamId {
21    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
22        f.write_str(&self.0)
23    }
24}
25
26/// An opaque codec name, for the decoder; never interpreted here.
27#[derive(Clone, Debug, PartialEq, Eq, Hash, Serialize, Deserialize)]
28pub struct CodecId(pub String);
29
30/// Raw PCM, 32-bit float, little endian, interleaved.
31pub const PCM_F32LE: &str = "pcm/f32le";
32/// Raw PCM, signed 16-bit, little endian, interleaved.
33pub const PCM_S16LE: &str = "pcm/s16le";
34
35/// Live (frames as they are produced) or recorded (finite, seekable).
36#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
37pub enum StreamKind {
38    /// Frames as they are produced.
39    Live,
40    /// A finite stream of this many ticks.
41    Recorded {
42        /// The length in ticks of the stream's clock.
43        duration_ticks: u64,
44    },
45}
46
47/// What a stream is.
48#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
49pub struct StreamInfo {
50    /// The id.
51    pub id: StreamId,
52    /// A name for people.
53    pub name: String,
54    /// Live or recorded.
55    pub kind: StreamKind,
56    /// The codec.
57    pub codec: CodecId,
58    /// Parameters for the decoder, such as `sample_rate` and `channels`.
59    pub params: Vec<(String, String)>,
60    /// Ticks per second for frame timestamps.
61    pub clock_rate: u32,
62    /// Opaque app metadata (for example a stream class such as voice, or a group id).
63    pub meta: Option<Vec<u8>>,
64}
65
66impl StreamInfo {
67    /// A live raw PCM stream: 32-bit float, interleaved, timestamps in samples.
68    pub fn pcm_f32(id: &str, name: &str, sample_rate: u32, channels: u16) -> Self {
69        StreamInfo {
70            id: StreamId::new(id),
71            name: name.to_string(),
72            kind: StreamKind::Live,
73            codec: CodecId(PCM_F32LE.into()),
74            params: vec![("sample_rate".into(), sample_rate.to_string()), ("channels".into(), channels.to_string())],
75            clock_rate: sample_rate,
76            meta: None,
77        }
78    }
79
80    /// With opaque app metadata.
81    pub fn with_meta(mut self, meta: Vec<u8>) -> Self {
82        self.meta = Some(meta);
83        self
84    }
85
86    /// A decoder parameter.
87    pub fn param(&self, key: &str) -> Option<&str> {
88        self.params.iter().find(|(k, _)| k == key).map(|(_, v)| v.as_str())
89    }
90}
91
92/// One frame of a stream.
93#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
94pub struct Frame {
95    /// Sequence number; a jump shows lost frames.
96    pub seq: u64,
97    /// Presentation time in ticks.
98    pub pts: u64,
99    /// Length in ticks.
100    pub duration: u32,
101    /// A point where a new listener can start decoding.
102    pub key: bool,
103    /// The encoded bytes.
104    pub payload: Vec<u8>,
105    /// Opaque app metadata, for example a loop position marker.
106    pub meta: Option<Vec<u8>>,
107}
108
109impl Frame {
110    /// A key frame with no metadata.
111    pub fn new(seq: u64, pts: u64, duration: u32, payload: Vec<u8>) -> Self {
112        Frame { seq, pts, duration, key: true, payload, meta: None }
113    }
114
115    /// A raw PCM f32 frame from interleaved samples; `channels` gives the duration in samples.
116    pub fn pcm_f32(seq: u64, pts: u64, channels: u16, samples: &[f32]) -> Self {
117        let payload = samples.iter().flat_map(|s| s.to_le_bytes()).collect();
118        Frame::new(seq, pts, (samples.len() / channels.max(1) as usize) as u32, payload)
119    }
120
121    /// The samples of a raw PCM f32 frame.
122    pub fn f32_samples(&self) -> Vec<f32> {
123        self.payload.as_chunks::<4>().0.iter().map(|c| f32::from_le_bytes(*c)).collect()
124    }
125}
126
127/// What a listener receives.
128#[derive(Clone, Debug, PartialEq, Eq)]
129pub enum StreamEvent {
130    /// The next frame.
131    Frame(Frame),
132    /// Frames were lost (dropped by an overflow policy or the network) before the next one.
133    Gap {
134        /// How many sequence numbers were skipped.
135        missed: u64,
136    },
137    /// The stream's info changed.
138    InfoChanged(StreamInfo),
139    /// The stream is over.
140    Ended,
141}
142
143/// What happens when a listener's queue is full.
144#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize)]
145pub enum Overflow {
146    /// Drop the oldest queued frame.
147    DropOldest,
148    /// Drop everything queued and wait for the next key frame.
149    SkipToKey,
150    /// Disconnect the listener.
151    Disconnect,
152}
153
154/// How much a listener may queue.
155#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize)]
156pub struct BufferPolicy {
157    /// Most frames queued.
158    pub max_frames: usize,
159    /// What happens when it is full.
160    pub overflow: Overflow,
161}
162
163impl Default for BufferPolicy {
164    fn default() -> Self {
165        BufferPolicy { max_frames: 256, overflow: Overflow::DropOldest }
166    }
167}
168
169/// Where a subscription starts.
170#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize)]
171pub enum Start {
172    /// At the live edge (the next key frame). For a recorded stream, the beginning.
173    Live,
174    /// At this presentation time (recorded streams; the key frame at or before it).
175    At(u64),
176    /// At the beginning (recorded streams).
177    FromStart,
178}
179
180/// How to subscribe.
181#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize)]
182pub struct SubscribeOptions {
183    /// Where to start.
184    pub start: Start,
185    /// The queue on the publisher's side for this subscription.
186    pub buffer: BufferPolicy,
187}
188
189impl Default for SubscribeOptions {
190    fn default() -> Self {
191        SubscribeOptions { start: Start::Live, buffer: BufferPolicy::default() }
192    }
193}
194
195/// Why a stream call failed.
196#[derive(Clone, Debug, PartialEq, Eq, thiserror::Error)]
197pub enum StreamError {
198    /// The publisher finished the stream.
199    #[error("the stream has ended")]
200    Ended,
201    /// The publisher refused the subscription.
202    #[error("refused: {0}")]
203    Refused(String),
204    /// No such stream.
205    #[error("unknown stream")]
206    UnknownStream,
207    /// The listener was disconnected by its overflow policy.
208    #[error("disconnected: the listener fell too far behind")]
209    Overrun,
210    /// A network failure.
211    #[error("network: {0}")]
212    Net(String),
213    /// The other side sent something this version does not understand.
214    #[error("protocol: {0}")]
215    Protocol(String),
216}