Skip to main content

srt_runtime/packet/
ack.rs

1//! ACK (Acknowledgment) control packet — `draft-sharabayko-srt-01` §3.2.4,
2//! Figure 13.
3//!
4//! Three variants share the same header shape and differ only in how much of
5//! the CIF is present, distinguished by CIF length on the wire:
6//!
7//! - **Full** (28-byte CIF): all seven fields, sent every 10 ms.
8//! - **Small** (16-byte CIF): fields up to and including Available Buffer
9//!   Size.
10//! - **Light** (4-byte CIF): only Last Acknowledged Packet Sequence Number.
11
12use super::number::{AckNumber, SeqNo, SocketId, SrtTimestamp};
13use super::{Error, Result, put_be32};
14
15/// CIF length, in bytes, of a Full ACK (§3.2.4).
16pub const ACK_CIF_LEN_FULL: usize = 28;
17/// CIF length, in bytes, of a Small ACK (§3.2.4).
18pub const ACK_CIF_LEN_SMALL: usize = 16;
19/// CIF length, in bytes, of a Light ACK (§3.2.4).
20pub const ACK_CIF_LEN_LIGHT: usize = 4;
21
22/// Byte offsets of the ACK CIF fields, in the Full/Small order of
23/// §3.2.4 Figure 13.
24const CIF_RTT_OFFSET: usize = 4;
25const CIF_RTT_VAR_OFFSET: usize = 8;
26const CIF_AVAIL_BUF_OFFSET: usize = 12;
27const CIF_PKT_RECV_RATE_OFFSET: usize = 16;
28const CIF_EST_LINK_CAPACITY_OFFSET: usize = 20;
29const CIF_RECV_RATE_OFFSET: usize = 24;
30
31/// The ACK Control Information Field — its shape (Full/Small/Light) is
32/// selected by which fields are present on the wire (§3.2.4). Data-carrying
33/// ADT: see [`AckPacket`] for the label convention rationale.
34#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
35#[cfg_attr(feature = "serde", derive(serde::Serialize))]
36#[non_exhaustive]
37pub enum AckCif {
38    /// Full ACK — all seven CIF fields.
39    Full {
40        /// Last Acknowledged Packet Sequence Number.
41        last_ack_seq: SeqNo,
42        /// RTT estimate, in microseconds.
43        rtt_us: u32,
44        /// RTT variance, in microseconds.
45        rtt_var_us: u32,
46        /// Available receiver buffer size, in packets.
47        avail_buf_size: u32,
48        /// Packets receiving rate, in packets per second.
49        pkt_recv_rate: u32,
50        /// Estimated link capacity, in packets per second.
51        est_link_capacity: u32,
52        /// Estimated receiving rate, in bytes per second.
53        recv_rate_bps: u32,
54    },
55    /// Small ACK — fields up to and including Available Buffer Size.
56    Small {
57        /// Last Acknowledged Packet Sequence Number.
58        last_ack_seq: SeqNo,
59        /// RTT estimate, in microseconds.
60        rtt_us: u32,
61        /// RTT variance, in microseconds.
62        rtt_var_us: u32,
63        /// Available receiver buffer size, in packets.
64        avail_buf_size: u32,
65    },
66    /// Light ACK — only Last Acknowledged Packet Sequence Number.
67    Light {
68        /// Last Acknowledged Packet Sequence Number.
69        last_ack_seq: SeqNo,
70    },
71}
72
73/// ACK control packet (§3.2.4, Figure 13). `ack_number` occupies the header
74/// `Type-specific Information` word ("the sequential number of the full
75/// acknowledgment packet starting from 1") in full — a 32-bit
76/// [`AckNumber`]; per §3.2.4 it "should be set to 0" for Small/Light ACKs,
77/// but is stored and round-tripped verbatim regardless of variant.
78#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
79#[cfg_attr(feature = "serde", derive(serde::Serialize))]
80pub struct AckPacket {
81    /// Acknowledgement Number (§3.2.4, Figure 13).
82    pub ack_number: AckNumber,
83    /// Timestamp (§3).
84    pub timestamp: SrtTimestamp,
85    /// Destination Socket ID (§3).
86    pub dest_socket_id: SocketId,
87    /// The CIF, shaped per variant.
88    pub cif: AckCif,
89}
90
91impl AckPacket {
92    pub(crate) fn parse_cif(
93        ack_number: u32,
94        timestamp: SrtTimestamp,
95        dest_socket_id: SocketId,
96        cif: &[u8],
97    ) -> Result<Self> {
98        let parsed = match cif.len() {
99            ACK_CIF_LEN_FULL => AckCif::Full {
100                last_ack_seq: SeqNo::from_wire_masked(
101                    broadcast_core::wire::Reader::at(cif, 0).u32("last_ack_seq")?,
102                ),
103                rtt_us: broadcast_core::wire::Reader::at(cif, CIF_RTT_OFFSET).u32("rtt_us")?,
104                rtt_var_us: broadcast_core::wire::Reader::at(cif, CIF_RTT_VAR_OFFSET)
105                    .u32("rtt_var_us")?,
106                avail_buf_size: broadcast_core::wire::Reader::at(cif, CIF_AVAIL_BUF_OFFSET)
107                    .u32("avail_buf_size")?,
108                pkt_recv_rate: broadcast_core::wire::Reader::at(cif, CIF_PKT_RECV_RATE_OFFSET)
109                    .u32("pkt_recv_rate")?,
110                est_link_capacity: broadcast_core::wire::Reader::at(
111                    cif,
112                    CIF_EST_LINK_CAPACITY_OFFSET,
113                )
114                .u32("est_link_capacity")?,
115                recv_rate_bps: broadcast_core::wire::Reader::at(cif, CIF_RECV_RATE_OFFSET)
116                    .u32("recv_rate_bps")?,
117            },
118            ACK_CIF_LEN_SMALL => AckCif::Small {
119                last_ack_seq: SeqNo::from_wire_masked(
120                    broadcast_core::wire::Reader::at(cif, 0).u32("last_ack_seq")?,
121                ),
122                rtt_us: broadcast_core::wire::Reader::at(cif, CIF_RTT_OFFSET).u32("rtt_us")?,
123                rtt_var_us: broadcast_core::wire::Reader::at(cif, CIF_RTT_VAR_OFFSET)
124                    .u32("rtt_var_us")?,
125                avail_buf_size: broadcast_core::wire::Reader::at(cif, CIF_AVAIL_BUF_OFFSET)
126                    .u32("avail_buf_size")?,
127            },
128            ACK_CIF_LEN_LIGHT => AckCif::Light {
129                last_ack_seq: SeqNo::from_wire_masked(
130                    broadcast_core::wire::Reader::at(cif, 0).u32("last_ack_seq")?,
131                ),
132            },
133            other => return Err(Error::InvalidAckLength { len: other }),
134        };
135        Ok(AckPacket {
136            ack_number: AckNumber::from_wire(ack_number),
137            timestamp,
138            dest_socket_id,
139            cif: parsed,
140        })
141    }
142
143    pub(crate) fn cif_len(&self) -> usize {
144        match self.cif {
145            AckCif::Full { .. } => ACK_CIF_LEN_FULL,
146            AckCif::Small { .. } => ACK_CIF_LEN_SMALL,
147            AckCif::Light { .. } => ACK_CIF_LEN_LIGHT,
148        }
149    }
150
151    pub(crate) fn write_cif(&self, buf: &mut [u8]) -> Result<()> {
152        match self.cif {
153            AckCif::Full {
154                last_ack_seq,
155                rtt_us,
156                rtt_var_us,
157                avail_buf_size,
158                pkt_recv_rate,
159                est_link_capacity,
160                recv_rate_bps,
161            } => {
162                put_be32(buf, 0, last_ack_seq.value());
163                put_be32(buf, CIF_RTT_OFFSET, rtt_us);
164                put_be32(buf, CIF_RTT_VAR_OFFSET, rtt_var_us);
165                put_be32(buf, CIF_AVAIL_BUF_OFFSET, avail_buf_size);
166                put_be32(buf, CIF_PKT_RECV_RATE_OFFSET, pkt_recv_rate);
167                put_be32(buf, CIF_EST_LINK_CAPACITY_OFFSET, est_link_capacity);
168                put_be32(buf, CIF_RECV_RATE_OFFSET, recv_rate_bps);
169            }
170            AckCif::Small {
171                last_ack_seq,
172                rtt_us,
173                rtt_var_us,
174                avail_buf_size,
175            } => {
176                put_be32(buf, 0, last_ack_seq.value());
177                put_be32(buf, CIF_RTT_OFFSET, rtt_us);
178                put_be32(buf, CIF_RTT_VAR_OFFSET, rtt_var_us);
179                put_be32(buf, CIF_AVAIL_BUF_OFFSET, avail_buf_size);
180            }
181            AckCif::Light { last_ack_seq } => {
182                put_be32(buf, 0, last_ack_seq.value());
183            }
184        }
185        Ok(())
186    }
187}
188
189#[cfg(test)]
190mod tests {
191    use super::super::SrtPacket;
192    use super::super::control::ControlPacket;
193    use super::*;
194
195    const FULL_CIF: AckCif = AckCif::Full {
196        last_ack_seq: SeqNo::MAX,
197        rtt_us: 2,
198        rtt_var_us: 3,
199        avail_buf_size: 4,
200        pkt_recv_rate: 5,
201        est_link_capacity: 6,
202        recv_rate_bps: 7,
203    };
204
205    #[test]
206    fn full_ack_round_trips_hand_computed_bytes() {
207        let pkt = ControlPacket::Ack(AckPacket {
208            ack_number: AckNumber::from_wire(42),
209            timestamp: SrtTimestamp::from_wire(1000),
210            dest_socket_id: SocketId::from_wire(2000),
211            cif: AckCif::Full {
212                last_ack_seq: SeqNo::from_wire_masked(1),
213                rtt_us: 2,
214                rtt_var_us: 3,
215                avail_buf_size: 4,
216                pkt_recv_rate: 5,
217                est_link_capacity: 6,
218                recv_rate_bps: 7,
219            },
220        });
221        let mut buf = [0u8; 16 + 28];
222        let n = pkt.serialize_into(&mut buf).unwrap();
223        assert_eq!(n, 44);
224        assert_eq!(buf[0], 0x80); // F=1
225        assert_eq!(&buf[0..4], &(0x8002_0000u32).to_be_bytes()); // control type=2
226        assert_eq!(&buf[4..8], &42u32.to_be_bytes());
227        assert_eq!(&buf[16..20], &1u32.to_be_bytes());
228        assert_eq!(&buf[40..44], &7u32.to_be_bytes());
229        assert_eq!(ControlPacket::parse(&buf).unwrap(), pkt);
230    }
231
232    #[test]
233    fn small_and_light_ack_round_trip() {
234        for cif in [
235            AckCif::Small {
236                last_ack_seq: SeqNo::from_wire_masked(10),
237                rtt_us: 20,
238                rtt_var_us: 30,
239                avail_buf_size: 40,
240            },
241            AckCif::Light {
242                last_ack_seq: SeqNo::from_wire_masked(99),
243            },
244        ] {
245            let pkt = ControlPacket::Ack(AckPacket {
246                ack_number: AckNumber::ZERO,
247                timestamp: SrtTimestamp::from_wire(1),
248                dest_socket_id: SocketId::from_wire(2),
249                cif,
250            });
251            let mut buf = alloc::vec![0u8; pkt.serialized_len()];
252            pkt.serialize_into(&mut buf).unwrap();
253            assert_eq!(ControlPacket::parse(&buf).unwrap(), pkt);
254        }
255    }
256
257    /// An Acknowledgement Number is a whole 32-bit `Type-specific
258    /// Information` word (§3.2.4, Figure 13): a value above the 31-bit
259    /// sequence space — which a peer can put on the wire and `parse` must
260    /// accept — still serializes back byte-identically. This was a fuzz
261    /// crash: the serializer bounded the field to 31 bits and refused a
262    /// packet `parse` had accepted.
263    #[test]
264    fn every_ack_number_a_peer_can_send_serializes_back() {
265        let mut ack = AckPacket {
266            ack_number: AckNumber::ZERO,
267            timestamp: SrtTimestamp::from_wire(1000),
268            dest_socket_id: SocketId::from_wire(2000),
269            cif: FULL_CIF,
270        };
271        for ack_number in [
272            0,
273            1,
274            u32::from(SeqNo::MAX),
275            u32::from(SeqNo::MAX) + 1,
276            // The ACK fuzz crash input (high bit set, all four bytes equal).
277            0x8E8E_8E8E,
278            u32::MAX,
279        ] {
280            ack.ack_number = AckNumber::from_wire(ack_number);
281            let mut buf = alloc::vec![0u8; ControlPacket::Ack(ack).serialized_len()];
282            assert_eq!(
283                ControlPacket::Ack(ack).serialize_into(&mut buf).unwrap(),
284                44
285            );
286            assert_eq!(&buf[4..8], &ack_number.to_be_bytes());
287            let parsed = ControlPacket::parse(&buf).unwrap();
288            assert_eq!(parsed, ControlPacket::Ack(ack));
289            assert_eq!(parsed.serialized_len(), buf.len());
290        }
291    }
292
293    /// The minimized ACK artifact from the fuzz crash, byte for byte: an
294    /// ACK whose Acknowledgement Number is `0x8E8E_8E8E`.
295    #[test]
296    fn fuzz_artifact_ack_round_trips() {
297        let bytes = [
298            128, 2, 0, 0, 142, 142, 142, 142, 142, 148, 142, 14, 142, 142, 142, 142, 142, 142, 142,
299            142,
300        ];
301        let parsed = SrtPacket::parse(&bytes).expect("parse accepts the fuzz input");
302        assert!(matches!(
303            &parsed,
304            SrtPacket::Control(ControlPacket::Ack(a))
305                if a.ack_number == AckNumber::from_wire(0x8E8E_8E8E)
306        ));
307        let mut buf = alloc::vec![0u8; parsed.serialized_len()];
308        assert_eq!(parsed.serialize_into(&mut buf).unwrap(), buf.len());
309        // The Acknowledgement Number bytes survive verbatim; the CIF's Last
310        // Acknowledged Packet Sequence Number keeps only its 31-bit value
311        // (top bit masked, see `last_ack_seq_top_bit_is_masked_at_parse`).
312        assert_eq!(&buf[4..8], &bytes[4..8]);
313        assert_eq!(SrtPacket::parse(&buf).unwrap(), parsed);
314    }
315
316    /// The Last Acknowledged Packet Sequence Number is 31 bits of its word
317    /// (the same packet-sequence space as a data packet's, §3.1): the top bit
318    /// is not a sequence value, so it is masked at the parse edge rather than
319    /// stored — the typed `SeqNo` cannot hold it, and serialize therefore
320    /// cannot refuse a number it previously accepted.
321    #[test]
322    fn last_ack_seq_top_bit_is_masked_at_parse() {
323        let mut buf = alloc::vec![0u8; 16 + 28];
324        ControlPacket::Ack(AckPacket {
325            ack_number: AckNumber::from_wire(1),
326            timestamp: SrtTimestamp::from_wire(2),
327            dest_socket_id: SocketId::from_wire(3),
328            cif: FULL_CIF,
329        })
330        .serialize_into(&mut buf)
331        .unwrap();
332        buf[16..20].copy_from_slice(&0xFFFF_FFFFu32.to_be_bytes());
333        let parsed = ControlPacket::parse(&buf).unwrap();
334        let ControlPacket::Ack(a) = parsed else {
335            panic!("an ACK");
336        };
337        assert_eq!(
338            a.cif,
339            AckCif::Full {
340                last_ack_seq: SeqNo::MAX,
341                rtt_us: 2,
342                rtt_var_us: 3,
343                avail_buf_size: 4,
344                pkt_recv_rate: 5,
345                est_link_capacity: 6,
346                recv_rate_bps: 7,
347            }
348        );
349        let mut out = alloc::vec![0u8; parsed.serialized_len()];
350        parsed.serialize_into(&mut out).unwrap();
351        assert_eq!(&out[16..20], &SeqNo::MAX.value().to_be_bytes());
352    }
353
354    #[test]
355    fn invalid_ack_cif_length_errs() {
356        let mut buf = [0u8; 16 + 5];
357        buf[0] = 0x80;
358        buf[1] = 0x02; // ACK
359        assert_eq!(
360            ControlPacket::parse(&buf).unwrap_err(),
361            Error::InvalidAckLength { len: 5 }
362        );
363    }
364
365    #[test]
366    fn mutate_field_changes_bytes() {
367        let mut pkt = AckPacket {
368            ack_number: AckNumber::from_wire(1),
369            timestamp: SrtTimestamp::from_wire(2),
370            dest_socket_id: SocketId::from_wire(3),
371            cif: AckCif::Light {
372                last_ack_seq: SeqNo::from_wire_masked(4),
373            },
374        };
375        let mut buf1 = [0u8; 20];
376        ControlPacket::Ack(pkt).serialize_into(&mut buf1).unwrap();
377        pkt.ack_number = AckNumber::from_wire(99);
378        let mut buf2 = [0u8; 20];
379        ControlPacket::Ack(pkt).serialize_into(&mut buf2).unwrap();
380        assert_ne!(buf1, buf2);
381    }
382}