-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathofferer.go
107 lines (86 loc) · 2.36 KB
/
offerer.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
105
106
107
package wamp_webrtc_go
import (
"encoding/json"
"github.com/pion/webrtc/v4"
log "github.com/sirupsen/logrus"
"github.com/xconnio/xconn-go"
)
type Offerer struct {
connection *webrtc.PeerConnection
channel chan *webrtc.DataChannel
}
func NewOfferer() *Offerer {
return &Offerer{
channel: make(chan *webrtc.DataChannel, 1),
}
}
func (o *Offerer) Offer(offerConfig *OfferConfig, session *xconn.Session, requestID string) (*Offer, error) {
// Prepare the configuration
config := webrtc.Configuration{
ICEServers: offerConfig.ICEServers,
}
// Create a new RTCPeerConnection
peerConnection, err := webrtc.NewPeerConnection(config)
if err != nil {
return nil, err
}
peerConnection.OnICECandidate(func(candidate *webrtc.ICECandidate) {
if candidate != nil {
answerData, err := json.Marshal(candidate.ToJSON())
if err != nil {
log.Errorf("failed to marshal answer: %v", err)
return
}
_ = session.Publish(offerConfig.TopicAnswererOnCandidate,
[]any{requestID, string(answerData)}, nil, nil)
}
})
o.connection = peerConnection
options := &webrtc.DataChannelInit{
Ordered: &offerConfig.Ordered,
Protocol: &offerConfig.Protocol,
ID: &offerConfig.ID,
}
dc, err := peerConnection.CreateDataChannel("data", options)
if err != nil {
return nil, err
}
dc.OnOpen(func() {
o.channel <- dc
})
// Set the handler for Peer connection state
// This will notify you when the peer has connected/disconnected
peerConnection.OnConnectionStateChange(func(s webrtc.PeerConnectionState) {
log.Debugf("Peer Connection State has changed: %s\n", s.String())
})
// Create a new offer
offer, err := peerConnection.CreateOffer(nil)
if err != nil {
return nil, err
}
// Set the offer as the local description
err = peerConnection.SetLocalDescription(offer)
if err != nil {
return nil, err
}
return &Offer{
Description: offer,
}, nil
}
func (o *Offerer) HandleAnswer(answer Answer) error {
if err := o.connection.SetRemoteDescription(answer.Description); err != nil {
return err
}
for _, candidate := range answer.Candidates {
if err := o.connection.AddICECandidate(candidate); err != nil {
return err
}
}
return nil
}
func (o *Offerer) AddICECandidate(candidate webrtc.ICECandidateInit) error {
return o.connection.AddICECandidate(candidate)
}
func (o *Offerer) WaitReady() chan *webrtc.DataChannel {
return o.channel
}