-
Notifications
You must be signed in to change notification settings - Fork 0
/
sequencer.go
60 lines (49 loc) · 1.32 KB
/
sequencer.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
// SPDX-FileCopyrightText: 2023 The Pion community <https://pion.ly>
// SPDX-License-Identifier: MIT
package rtp
import (
"math"
"sync"
)
// Sequencer generates sequential sequence numbers for building RTP packets
type Sequencer interface {
NextSequenceNumber() uint16
RollOverCount() uint64
}
// NewRandomSequencer returns a new sequencer starting from a random sequence
// number
func NewRandomSequencer() Sequencer {
return &sequencer{
sequenceNumber: uint16(globalMathRandomGenerator.Intn(math.MaxUint16)),
}
}
// NewFixedSequencer returns a new sequencer starting from a specific
// sequence number
func NewFixedSequencer(s uint16) Sequencer {
return &sequencer{
sequenceNumber: s - 1, // -1 because the first sequence number prepends 1
}
}
type sequencer struct {
sequenceNumber uint16
rollOverCount uint64
mutex sync.Mutex
}
// NextSequenceNumber increment and returns a new sequence number for
// building RTP packets
func (s *sequencer) NextSequenceNumber() uint16 {
s.mutex.Lock()
defer s.mutex.Unlock()
s.sequenceNumber++
if s.sequenceNumber == 0 {
s.rollOverCount++
}
return s.sequenceNumber
}
// RollOverCount returns the amount of times the 16bit sequence number
// has wrapped
func (s *sequencer) RollOverCount() uint64 {
s.mutex.Lock()
defer s.mutex.Unlock()
return s.rollOverCount
}