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