-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathice.go
104 lines (85 loc) · 2.02 KB
/
ice.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
100
101
102
103
104
package main
import (
"context"
"fmt"
"log"
"sync"
"github.com/pion/webrtc/v3"
)
func gatherICE(ctx context.Context, peer *webrtc.PeerConnection, signal interface{}) <-chan struct{} {
done := make(chan struct{})
switch si, ok := signal.(SignalICE); ok {
case true:
go func() {
defer close(done)
trickleICEWLog(ctx, peer, si)
}()
case false:
defer close(done)
chanRecv(ctx, webrtc.GatheringCompletePromise(peer))
}
return done
}
func trickleICEWLog(ctx context.Context, peer *webrtc.PeerConnection, s SignalICE) {
for {
if ctx.Err() != nil {
break
}
err, ok := <-trickleICE(ctx, peer, s)
if !ok {
break
}
if err != nil {
log.Println("trickle ICE failed:", err)
}
}
}
func trickleICE(ctx context.Context, peer *webrtc.PeerConnection, s SignalICE) <-chan error {
errc := make(chan error)
once := sync.Once{}
ctx, cancel := context.WithCancel(ctx)
peer.OnICEGatheringStateChange(func(is webrtc.ICEGathererState) {
if is == webrtc.ICEGathererStateNew || is == webrtc.ICEGathererStateGathering {
return
}
cancel()
once.Do(func() { close(errc) })
})
peer.OnICECandidate(func(i *webrtc.ICECandidate) {
if ctx.Err() != nil {
return
}
err := s.SendICECandidate(ctx, i)
if err != nil {
chanSend(ctx, errc, fmt.Errorf("send ICE candidate failed: %w", err))
}
})
go func() {
deffered := make([]*webrtc.ICECandidateInit, 0, 10)
for {
if ctx.Err() != nil {
break
}
if peer.RemoteDescription() != nil && len(deffered) > 0 {
for _, can := range deffered {
if err := peer.AddICECandidate(*can); err != nil {
chanSend(ctx, errc, fmt.Errorf("add ICE candidate failed: %w", err))
}
}
deffered = deffered[:0]
}
can, err := s.RecvICECandidate(ctx)
if err != nil {
break
}
if peer.RemoteDescription() == nil {
deffered = append(deffered, can)
continue
}
if err = peer.AddICECandidate(*can); err != nil {
chanSend(ctx, errc, fmt.Errorf("add ICE candidate failed: %w", err))
}
}
}()
return errc
}