/
rtp_sort.go
98 lines (81 loc) · 1.69 KB
/
rtp_sort.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
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
package utils
import (
"container/heap"
"errors"
"github.com/pion/rtp"
)
const MaxRtpDiff = 65000 //相邻两个包之间的最大差值
type PriorityQueueRtp struct {
itemHeap *packets
current *rtp.Packet
priorityMap map[uint16]bool
lastPacket *rtp.Packet
}
func NewPqRtp() *PriorityQueueRtp {
return &PriorityQueueRtp{
itemHeap: &packets{},
priorityMap: make(map[uint16]bool),
}
}
func (p *PriorityQueueRtp) Len() int {
return p.itemHeap.Len()
}
func (p *PriorityQueueRtp) Push(v rtp.Packet) {
if p.priorityMap[v.SequenceNumber] {
return
}
newItem := &packet{
value: v,
priority: v.SequenceNumber,
}
heap.Push(p.itemHeap, newItem)
}
func (p *PriorityQueueRtp) Pop() (rtp.Packet, error) {
if len(*p.itemHeap) == 0 {
return rtp.Packet{}, errors.New("empty queue")
}
item := heap.Pop(p.itemHeap).(*packet)
return item.value, nil
}
func (p *PriorityQueueRtp) Empty() {
old := *p.itemHeap
*p.itemHeap = old[:0]
}
type packets []*packet
type packet struct {
value rtp.Packet
priority uint16
index int
}
func (p *packets) Len() int {
return len(*p)
}
func (p *packets) Less(i, j int) bool {
a, b := (*p)[i].priority, (*p)[j].priority
if int(a)-int(b) > MaxRtpDiff || int(b)-int(a) > MaxRtpDiff {
if a < b {
return false
}
return true
}
return a < b
}
func (p *packets) Swap(i, j int) {
(*p)[i], (*p)[j] = (*p)[j], (*p)[i]
(*p)[i].index = i
(*p)[j].index = j
}
func (p *packets) Push(x interface{}) {
it := x.(*packet)
it.index = len(*p)
*p = append(*p, it)
}
func (p *packets) Pop() interface{} {
old := *p
n := len(old)
item := old[n-1]
old[n-1] = nil // avoid memory leak
item.index = -1 // for safety
*p = old[0 : n-1]
return item
}