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