Skip to main content

rtci_rtp/
sequence.rs

1use std::fmt;
2use std::sync::Arc;
3use std::sync::atomic::{AtomicU16, AtomicU64, Ordering};
4
5/// Sequencer generates sequential sequence numbers for building RTP packets
6pub trait Sequencer: Send + Sync + fmt::Debug {
7    /// Returns the next sequence number, wrapping at `u16::MAX` and counting the rollover.
8    fn next_sequence_number(&self) -> u16;
9    /// How many times the sequence number has wrapped.
10    ///
11    /// SRTP needs this: the rollover counter is part of the packet index it encrypts with.
12    fn roll_over_count(&self) -> u64;
13    /// Clones this sequencer behind a trait object.
14    fn clone_to(&self) -> Box<dyn Sequencer>;
15}
16
17impl Clone for Box<dyn Sequencer> {
18    fn clone(&self) -> Box<dyn Sequencer> {
19        self.clone_to()
20    }
21}
22
23/// NewRandomSequencer returns a new sequencer starting from a random sequence
24/// number
25pub fn new_random_sequencer() -> impl Sequencer {
26    let c = Counters {
27        sequence_number: Arc::new(AtomicU16::new(rand::random::<u16>())),
28        roll_over_count: Arc::new(AtomicU64::new(0)),
29    };
30    SequencerImpl(c)
31}
32
33/// NewFixedSequencer returns a new sequencer starting from a specific
34/// sequence number
35pub fn new_fixed_sequencer(s: u16) -> impl Sequencer {
36    let sequence_number = if s == 0 { u16::MAX } else { s - 1 };
37
38    let c = Counters {
39        sequence_number: Arc::new(AtomicU16::new(sequence_number)),
40        roll_over_count: Arc::new(AtomicU64::new(0)),
41    };
42
43    SequencerImpl(c)
44}
45
46#[derive(Debug, Clone)]
47struct SequencerImpl(Counters);
48
49#[derive(Debug, Clone)]
50struct Counters {
51    sequence_number: Arc<AtomicU16>,
52    roll_over_count: Arc<AtomicU64>,
53}
54
55impl Sequencer for SequencerImpl {
56    /// NextSequenceNumber increment and returns a new sequence number for
57    /// building RTP packets
58    fn next_sequence_number(&self) -> u16 {
59        if self.0.sequence_number.load(Ordering::SeqCst) == u16::MAX {
60            self.0.roll_over_count.fetch_add(1, Ordering::SeqCst);
61            self.0.sequence_number.store(0, Ordering::SeqCst);
62            0
63        } else {
64            self.0.sequence_number.fetch_add(1, Ordering::SeqCst) + 1
65        }
66    }
67
68    /// RollOverCount returns the amount of times the 16bit sequence number
69    /// has wrapped
70    fn roll_over_count(&self) -> u64 {
71        self.0.roll_over_count.load(Ordering::SeqCst)
72    }
73
74    fn clone_to(&self) -> Box<dyn Sequencer> {
75        Box::new(self.clone())
76    }
77}
78
79/// A source is valid once this many packets arrived in sequence (RFC 3550 Appendix A.1).
80pub const MIN_SEQUENTIAL: u32 = 2;
81/// A forward jump smaller than this is loss, not a restart (RFC 3550 Appendix A.1).
82pub const MAX_DROPOUT: u16 = 3000;
83/// A packet this far behind the highest sequence number, or less, is late or a duplicate
84/// (RFC 3550 Appendix A.1).
85pub const MAX_MISORDER: u16 = 100;
86
87const RTP_SEQ_MOD: u32 = 1 << 16;
88
89/// The per-source sequence number state of RFC 3550 Appendix A.1 (`init_seq`, `update_seq`),
90/// with the loss arithmetic of Appendix A.3.
91///
92/// A new source is on probation until [`MIN_SEQUENTIAL`] packets arrive in sequence; a jump of
93/// [`MAX_DROPOUT`] or more ahead, or more than [`MAX_MISORDER`] behind, is taken for a source
94/// that restarted once two packets in a row say so, and the state starts over from there.
95#[derive(Debug, Clone, PartialEq, Eq)]
96pub struct SourceSequence {
97    max_seq: u16,
98    cycles: u32,
99    base_seq: u32,
100    bad_seq: u32,
101    probation: u32,
102    received: u32,
103}
104
105impl SourceSequence {
106    /// The state for a source whose first packet has this sequence number. That packet is
107    /// counted by the first [`update`](SourceSequence::update), not here.
108    pub fn new(first_sequence_number: u16) -> Self {
109        let mut state = SourceSequence {
110            max_seq: 0,
111            cycles: 0,
112            base_seq: 0,
113            bad_seq: 0,
114            probation: MIN_SEQUENTIAL,
115            received: 0,
116        };
117        state.init(first_sequence_number);
118        state.max_seq = first_sequence_number.wrapping_sub(1);
119        state
120    }
121
122    fn init(&mut self, sequence_number: u16) {
123        self.base_seq = u32::from(sequence_number);
124        self.max_seq = sequence_number;
125        // Not a sequence number: so that `seq == bad_seq` is false.
126        self.bad_seq = RTP_SEQ_MOD + 1;
127        self.cycles = 0;
128        self.received = 0;
129    }
130
131    /// Takes a packet's sequence number. `true` when the packet is valid: in sequence for a
132    /// source past its probation, late or duplicated within [`MAX_MISORDER`]. `false` while the
133    /// source is on probation, and for a packet after a jump until the next one confirms it.
134    pub fn update(&mut self, sequence_number: u16) -> bool {
135        let udelta = sequence_number.wrapping_sub(self.max_seq);
136        if self.probation > 0 {
137            // The source is not valid until MIN_SEQUENTIAL packets with sequential sequence
138            // numbers have been received.
139            if sequence_number == self.max_seq.wrapping_add(1) {
140                self.probation -= 1;
141                self.max_seq = sequence_number;
142                if self.probation == 0 {
143                    self.init(sequence_number);
144                    self.received += 1;
145                    return true;
146                }
147            } else {
148                self.probation = MIN_SEQUENTIAL - 1;
149                self.max_seq = sequence_number;
150            }
151            return false;
152        } else if udelta < MAX_DROPOUT {
153            // In order, with a permissible gap.
154            if sequence_number < self.max_seq {
155                // The sequence number wrapped: count another 64K cycle.
156                self.cycles = self.cycles.wrapping_add(RTP_SEQ_MOD);
157            }
158            self.max_seq = sequence_number;
159        } else if u32::from(udelta) <= RTP_SEQ_MOD - u32::from(MAX_MISORDER) {
160            // The sequence number made a very large jump.
161            if u32::from(sequence_number) == self.bad_seq {
162                // Two sequential packets: the other side restarted without telling us, so
163                // re-sync as if this were the first packet.
164                self.init(sequence_number);
165            } else {
166                self.bad_seq = (u32::from(sequence_number) + 1) & (RTP_SEQ_MOD - 1);
167                return false;
168            }
169        } else {
170            // A duplicate or a reordered packet.
171        }
172        self.received = self.received.wrapping_add(1);
173        true
174    }
175
176    /// Whether the source is still on probation.
177    pub fn on_probation(&self) -> bool {
178        self.probation > 0
179    }
180
181    /// The extended highest sequence number: the count of sequence number cycles in the high
182    /// 16 bits (RFC 3550 section 6.4.1).
183    pub fn extended_max(&self) -> u32 {
184        self.cycles.wrapping_add(u32::from(self.max_seq))
185    }
186
187    /// Packets accepted since the state was last initialised.
188    pub fn received(&self) -> u32 {
189        self.received
190    }
191
192    /// Packets expected: from the first sequence number to the highest (Appendix A.3).
193    pub fn expected(&self) -> u32 {
194        self.extended_max()
195            .wrapping_sub(self.base_seq)
196            .wrapping_add(1)
197    }
198
199    /// Packets lost: expected less received. Negative when duplicates arrived; a late packet
200    /// is not lost (RFC 3550 section 6.4.1, Appendix A.3).
201    pub fn cumulative_lost(&self) -> i64 {
202        i64::from(self.expected()) - i64::from(self.received)
203    }
204}
205
206#[cfg(test)]
207#[path = "sequence_test.rs"]
208mod sequence_test;