candidatepair.go 2.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899
  1. package ice
  2. import (
  3. "fmt"
  4. "github.com/pion/stun"
  5. )
  6. func newCandidatePair(local, remote Candidate, controlling bool) *CandidatePair {
  7. return &CandidatePair{
  8. iceRoleControlling: controlling,
  9. Remote: remote,
  10. Local: local,
  11. state: CandidatePairStateWaiting,
  12. }
  13. }
  14. // CandidatePair is a combination of a
  15. // local and remote candidate
  16. type CandidatePair struct {
  17. iceRoleControlling bool
  18. Remote Candidate
  19. Local Candidate
  20. bindingRequestCount uint16
  21. state CandidatePairState
  22. nominated bool
  23. nominateOnBindingSuccess bool
  24. }
  25. func (p *CandidatePair) String() string {
  26. if p == nil {
  27. return ""
  28. }
  29. return fmt.Sprintf("prio %d (local, prio %d) %s <-> %s (remote, prio %d)",
  30. p.priority(), p.Local.Priority(), p.Local, p.Remote, p.Remote.Priority())
  31. }
  32. func (p *CandidatePair) equal(other *CandidatePair) bool {
  33. if p == nil && other == nil {
  34. return true
  35. }
  36. if p == nil || other == nil {
  37. return false
  38. }
  39. return p.Local.Equal(other.Local) && p.Remote.Equal(other.Remote)
  40. }
  41. // RFC 5245 - 5.7.2. Computing Pair Priority and Ordering Pairs
  42. // Let G be the priority for the candidate provided by the controlling
  43. // agent. Let D be the priority for the candidate provided by the
  44. // controlled agent.
  45. // pair priority = 2^32*MIN(G,D) + 2*MAX(G,D) + (G>D?1:0)
  46. func (p *CandidatePair) priority() uint64 {
  47. var g, d uint32
  48. if p.iceRoleControlling {
  49. g = p.Local.Priority()
  50. d = p.Remote.Priority()
  51. } else {
  52. g = p.Remote.Priority()
  53. d = p.Local.Priority()
  54. }
  55. // Just implement these here rather
  56. // than fooling around with the math package
  57. min := func(x, y uint32) uint64 {
  58. if x < y {
  59. return uint64(x)
  60. }
  61. return uint64(y)
  62. }
  63. max := func(x, y uint32) uint64 {
  64. if x > y {
  65. return uint64(x)
  66. }
  67. return uint64(y)
  68. }
  69. cmp := func(x, y uint32) uint64 {
  70. if x > y {
  71. return uint64(1)
  72. }
  73. return uint64(0)
  74. }
  75. // 1<<32 overflows uint32; and if both g && d are
  76. // maxUint32, this result would overflow uint64
  77. return (1<<32-1)*min(g, d) + 2*max(g, d) + cmp(g, d)
  78. }
  79. func (p *CandidatePair) Write(b []byte) (int, error) {
  80. return p.Local.writeTo(b, p.Remote)
  81. }
  82. func (a *Agent) sendSTUN(msg *stun.Message, local, remote Candidate) {
  83. _, err := local.writeTo(msg.Raw, remote)
  84. if err != nil {
  85. a.log.Tracef("failed to send STUN message: %s", err)
  86. }
  87. }