-
Notifications
You must be signed in to change notification settings - Fork 0
/
candidatepair.go
99 lines (87 loc) · 2.35 KB
/
candidatepair.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
99
package ice
import (
"fmt"
"github.com/pion/stun"
)
func newCandidatePair(local, remote Candidate, controlling bool) *CandidatePair {
return &CandidatePair{
iceRoleControlling: controlling,
Remote: remote,
Local: local,
state: CandidatePairStateWaiting,
}
}
// CandidatePair is a combination of a
// local and remote candidate
type CandidatePair struct {
iceRoleControlling bool
Remote Candidate
Local Candidate
bindingRequestCount uint16
state CandidatePairState
nominated bool
nominateOnBindingSuccess bool
}
func (p *CandidatePair) String() string {
if p == nil {
return ""
}
return fmt.Sprintf("prio %d (local, prio %d) %s <-> %s (remote, prio %d)",
p.priority(), p.Local.Priority(), p.Local, p.Remote, p.Remote.Priority())
}
func (p *CandidatePair) equal(other *CandidatePair) bool {
if p == nil && other == nil {
return true
}
if p == nil || other == nil {
return false
}
return p.Local.Equal(other.Local) && p.Remote.Equal(other.Remote)
}
// RFC 5245 - 5.7.2. Computing Pair Priority and Ordering Pairs
// Let G be the priority for the candidate provided by the controlling
// agent. Let D be the priority for the candidate provided by the
// controlled agent.
// pair priority = 2^32*MIN(G,D) + 2*MAX(G,D) + (G>D?1:0)
func (p *CandidatePair) priority() uint64 {
var g, d uint32
if p.iceRoleControlling {
g = p.Local.Priority()
d = p.Remote.Priority()
} else {
g = p.Remote.Priority()
d = p.Local.Priority()
}
// Just implement these here rather
// than fooling around with the math package
min := func(x, y uint32) uint64 {
if x < y {
return uint64(x)
}
return uint64(y)
}
max := func(x, y uint32) uint64 {
if x > y {
return uint64(x)
}
return uint64(y)
}
cmp := func(x, y uint32) uint64 {
if x > y {
return uint64(1)
}
return uint64(0)
}
// 1<<32 overflows uint32; and if both g && d are
// maxUint32, this result would overflow uint64
return (1<<32-1)*min(g, d) + 2*max(g, d) + cmp(g, d)
}
func (p *CandidatePair) Write(b []byte) (int, error) {
return p.Local.writeTo(b, p.Remote)
}
func (a *Agent) sendSTUN(msg *stun.Message, local, remote Candidate) {
_, err := local.writeTo(msg.Raw, remote)
if err != nil {
a.log.Tracef("failed to send STUN message: %s", err)
}
}