Skip to main content

rtmp_runtime/
ids.rs

1//! The RTMP wire identities — §5.1.2 `chunk stream id`, §5.1.3 `message
2//! stream id` and `timestamp`, §5.3.1.1's basic-header encodability rule
3//! (reference `private/specs-verified/rtmp/rtmp-runtime/rtmp.md`).
4//!
5//! Each is a fixed-width wire field with no invalid bit pattern, so every bit
6//! pattern round-trips byte-exactly; the types exist so a chunk stream id
7//! cannot be passed where a message stream id is expected (the RTMP trap: both
8//! are bare integers in the spec) and so the basic-header range lives with the
9//! id it constrains.
10
11use core::time::Duration;
12
13/// Lowest chunk stream id a basic header can carry; 0 and 1 are the 2-/3-byte
14/// form markers, not ids (§5.3.1.1).
15pub const MIN_CHUNK_STREAM_ID: u32 = 2;
16
17/// Highest chunk stream id a basic header can carry: the 3-byte form encodes
18/// `(byte2 * 256) + byte1 + 64` (§5.3.1.1).
19pub const MAX_CHUNK_STREAM_ID: u32 = 65_599;
20
21/// Chunk stream id (csid) — the per-chunk-stream multiplexing identity
22/// (§5.1.2), carried by the basic header in the range 2..=65599.
23#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash, Default)]
24#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
25#[repr(transparent)]
26pub struct ChunkStreamId(u32);
27
28impl ChunkStreamId {
29    /// Wrap a chunk stream id as read from, or written to, the wire. Every
30    /// `u32` is representable as a value; [`basic_header_encodable`] says
31    /// whether a basic header can carry it.
32    ///
33    /// [`basic_header_encodable`]: Self::basic_header_encodable
34    #[must_use]
35    pub const fn new(raw: u32) -> Self {
36        Self(raw)
37    }
38
39    /// The raw id.
40    #[must_use]
41    pub const fn get(self) -> u32 {
42        self.0
43    }
44
45    /// Whether a basic header can carry this id (2..=65599, §5.3.1.1).
46    #[must_use]
47    pub const fn basic_header_encodable(self) -> bool {
48        self.0 >= MIN_CHUNK_STREAM_ID && self.0 <= MAX_CHUNK_STREAM_ID
49    }
50}
51
52impl From<u32> for ChunkStreamId {
53    fn from(raw: u32) -> Self {
54        Self(raw)
55    }
56}
57
58impl From<ChunkStreamId> for u32 {
59    fn from(id: ChunkStreamId) -> Self {
60        id.0
61    }
62}
63
64impl core::fmt::Display for ChunkStreamId {
65    fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
66        write!(f, "{}", self.0)
67    }
68}
69
70/// Message stream id (msid) — the application-level stream a message belongs
71/// to (§5.1.3), allocated by `createStream` and carried little-endian in a
72/// Type 0 message header.
73#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash, Default)]
74#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
75#[repr(transparent)]
76pub struct MessageStreamId(u32);
77
78impl MessageStreamId {
79    /// Wrap a raw message stream id from the wire or a `createStream` result.
80    #[must_use]
81    pub const fn new(raw: u32) -> Self {
82        Self(raw)
83    }
84
85    /// The raw id.
86    #[must_use]
87    pub const fn get(self) -> u32 {
88        self.0
89    }
90}
91
92impl From<u32> for MessageStreamId {
93    fn from(raw: u32) -> Self {
94        Self(raw)
95    }
96}
97
98impl From<MessageStreamId> for u32 {
99    fn from(id: MessageStreamId) -> Self {
100        id.0
101    }
102}
103
104impl core::fmt::Display for MessageStreamId {
105    fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
106        write!(f, "{}", self.0)
107    }
108}
109
110/// An RTMP acknowledgement sequence number (§5.4.3): the total number of
111/// bytes received so far, carried as a 32-bit field.
112#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash, Default)]
113#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
114#[repr(transparent)]
115pub struct SequenceNumber(u32);
116
117impl SequenceNumber {
118    /// Wrap a raw byte count from the wire.
119    #[must_use]
120    pub const fn new(raw: u32) -> Self {
121        Self(raw)
122    }
123
124    /// The raw byte count.
125    #[must_use]
126    pub const fn get(self) -> u32 {
127        self.0
128    }
129}
130
131impl From<u32> for SequenceNumber {
132    fn from(raw: u32) -> Self {
133        Self(raw)
134    }
135}
136
137impl From<SequenceNumber> for u32 {
138    fn from(seq: SequenceNumber) -> Self {
139        seq.0
140    }
141}
142
143impl core::fmt::Display for SequenceNumber {
144    fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
145        write!(f, "{}", self.0)
146    }
147}
148
149/// An RTMP `timestamp` / `timestamp delta` (§5.3.1.2) — a whole number of
150/// milliseconds on the wire, held as a span so a caller never passes a raw
151/// tick count.
152///
153/// The wire is a 24-bit field plus the 4-byte Extended Timestamp (§5.3.1.3),
154/// so any `Duration` below 2^32 ms converts exactly; a coarser `Duration`
155/// (sub-millisecond units) is rounded down to the millisecond the wire
156/// carries.
157#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash, Default)]
158#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
159pub struct Timestamp(Duration);
160
161impl Timestamp {
162    /// The zero timestamp (`Duration::ZERO`).
163    pub const ZERO: Self = Self(Duration::ZERO);
164
165    /// Build from a span, rejecting one the 32-bit wire field cannot hold
166    /// (2^32 ms is about 49.7 days).
167    ///
168    /// # Errors
169    /// [`TimestampOutOfRange`] when the span is 2^32 ms or longer.
170    pub fn try_new(span: Duration) -> Result<Self, TimestampOutOfRange> {
171        u32::try_from(span.as_millis())
172            .map(|_| Self(span))
173            .map_err(|_| TimestampOutOfRange)
174    }
175
176    /// The span this timestamp stands for.
177    #[must_use]
178    pub const fn span(self) -> Duration {
179        self.0
180    }
181
182    /// The whole milliseconds the wire carries.
183    #[must_use]
184    pub fn millis(self) -> u32 {
185        u32::try_from(self.0.as_millis()).unwrap_or(u32::MAX)
186    }
187
188    /// Read a value straight off the wire (always representable).
189    #[must_use]
190    pub const fn from_millis(millis: u32) -> Self {
191        Self(Duration::from_millis(millis as u64))
192    }
193
194    /// `self + delta`, or `None` when that leaves the 32-bit field.
195    #[must_use]
196    pub fn checked_add(self, delta: Duration) -> Option<Self> {
197        self.0
198            .checked_add(delta)
199            .and_then(|s| Self::try_new(s).ok())
200    }
201}
202
203impl From<Duration> for Timestamp {
204    fn from(span: Duration) -> Self {
205        Self(span)
206    }
207}
208
209impl From<Timestamp> for Duration {
210    fn from(ts: Timestamp) -> Self {
211        ts.0
212    }
213}
214
215impl core::fmt::Display for Timestamp {
216    fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
217        write!(f, "{} ms", self.millis())
218    }
219}
220
221/// A `Timestamp` the 32-bit wire field cannot hold (a span of 2^32 ms or more,
222/// §5.3.1.2).
223#[derive(Debug, Clone, Copy, PartialEq, Eq)]
224pub struct TimestampOutOfRange;
225
226impl core::fmt::Display for TimestampOutOfRange {
227    fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
228        f.write_str("RTMP timestamp does not fit the 32-bit wire field (max 2^32-1 ms)")
229    }
230}
231
232impl core::error::Error for TimestampOutOfRange {}
233
234#[cfg(test)]
235mod tests {
236    use super::*;
237
238    #[test]
239    fn chunk_stream_ids_mark_which_are_encodable() {
240        assert!(!ChunkStreamId::new(1).basic_header_encodable());
241        assert!(ChunkStreamId::new(MIN_CHUNK_STREAM_ID).basic_header_encodable());
242        assert!(ChunkStreamId::new(MAX_CHUNK_STREAM_ID).basic_header_encodable());
243        assert!(!ChunkStreamId::new(MAX_CHUNK_STREAM_ID + 1).basic_header_encodable());
244    }
245
246    #[test]
247    fn timestamps_round_trip_through_milliseconds() {
248        let ts = Timestamp::try_new(Duration::from_millis(3000)).unwrap();
249        assert_eq!(ts.millis(), 3000);
250        assert_eq!(ts.span(), Duration::from_millis(3000));
251        assert_eq!(Timestamp::from_millis(3000), ts);
252        assert_eq!(Duration::from(ts), Duration::from_millis(3000));
253    }
254
255    #[test]
256    fn a_timestamp_past_the_wire_width_is_rejected() {
257        assert_eq!(
258            Timestamp::try_new(Duration::from_millis(u64::from(u32::MAX) + 1)),
259            Err(TimestampOutOfRange)
260        );
261        assert!(Timestamp::try_new(Duration::from_millis(u64::from(u32::MAX))).is_ok());
262    }
263
264    #[test]
265    fn adding_a_delta_past_the_wire_width_is_none() {
266        let near_end = Timestamp::from_millis(u32::MAX);
267        assert_eq!(near_end.checked_add(Duration::from_millis(1)), None);
268        assert_eq!(
269            Timestamp::from_millis(1).checked_add(Duration::from_millis(1)),
270            Some(Timestamp::from_millis(2))
271        );
272    }
273
274    #[test]
275    fn ids_carry_their_raw_value() {
276        assert_eq!(ChunkStreamId::from(4).get(), 4);
277        assert_eq!(u32::from(MessageStreamId::new(0)), 0);
278        assert_eq!(ChunkStreamId::new(2).to_string(), "2");
279    }
280}