sequencer.go 1.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657
  1. package rtp
  2. import (
  3. "math"
  4. "sync"
  5. )
  6. // Sequencer generates sequential sequence numbers for building RTP packets
  7. type Sequencer interface {
  8. NextSequenceNumber() uint16
  9. RollOverCount() uint64
  10. }
  11. // NewRandomSequencer returns a new sequencer starting from a random sequence
  12. // number
  13. func NewRandomSequencer() Sequencer {
  14. return &sequencer{
  15. sequenceNumber: uint16(globalMathRandomGenerator.Intn(math.MaxUint16)),
  16. }
  17. }
  18. // NewFixedSequencer returns a new sequencer starting from a specific
  19. // sequence number
  20. func NewFixedSequencer(s uint16) Sequencer {
  21. return &sequencer{
  22. sequenceNumber: s - 1, // -1 because the first sequence number prepends 1
  23. }
  24. }
  25. type sequencer struct {
  26. sequenceNumber uint16
  27. rollOverCount uint64
  28. mutex sync.Mutex
  29. }
  30. // NextSequenceNumber increment and returns a new sequence number for
  31. // building RTP packets
  32. func (s *sequencer) NextSequenceNumber() uint16 {
  33. s.mutex.Lock()
  34. defer s.mutex.Unlock()
  35. s.sequenceNumber++
  36. if s.sequenceNumber == 0 {
  37. s.rollOverCount++
  38. }
  39. return s.sequenceNumber
  40. }
  41. // RollOverCount returns the amount of times the 16bit sequence number
  42. // has wrapped
  43. func (s *sequencer) RollOverCount() uint64 {
  44. s.mutex.Lock()
  45. defer s.mutex.Unlock()
  46. return s.rollOverCount
  47. }