forked from keroserene/go-webrtc
/
peerconnection.go
430 lines (370 loc) · 13.4 KB
/
peerconnection.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
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
/*
Package webrtc is a golang wrapper on native code WebRTC.
For consistency with the browser-based WebRTCs, the interface here is based
loosely on: w3c.github.io/webrtc-pc
The main goal of this project is to present a golang WebRTC package in the most
idiomatic and simple-to-use way.
However, to provide a better experience for users of this package, there are
differences inherent in the interface written here and the original native code
WebRTC - from the golang requirement of Capitalized identifiers for public
interfaces, to the replacement of certain callbacks with goroutines.
Note that building the necessary libwebrtc static library is excessively
complicated, which is why the necessary platform-specific archives will be
provided in lib/. This also mitigates the possibility that future commits on
native libwebrtc will break go-webrtc, because the interface with the native
code, through the intermediate CGO layer, is relatively fragile.
Due to other external goals of the developers, this package will only be
focused on DataChannels. However, extending this package to allow video/audio
media streams and related functionality, to be a "complete" WebRTC suite,
is entirely possible and will likely happen in the long term. (Issue #7)
This will however have implications for the archives that need to be built
and linked.
Please share any improvements or concerns as issues or pull requests on github.
*/
package webrtc
/*
#cgo CXXFLAGS: -std=c++0x
#cgo linux,amd64 pkg-config: webrtc-linux-amd64.pc
#cgo darwin,amd64 pkg-config: webrtc-darwin-amd64.pc
#include <stdlib.h> // Needed for C.free
#include "cpeerconnection.h"
#include "ctestenums.h"
*/
import "C"
import (
"errors"
"github.com/keroserene/go-webrtc/data"
"unsafe"
)
func init() {
SetLoggingVerbosity(3) // Default verbosity.
}
type (
PeerConnectionState int
IceGatheringState int
IceConnectionState int
)
const (
PeerConnectionStateNew PeerConnectionState = iota
PeerConnectionStateConnecting
PeerConnectionStateConnected
PeerConnectionStateDisconnected
PeerConnectionStateFailed
)
var PeerConnectionStateString = []string{
"New", "Connecting", "Connected", "Disconnected", "Failed"}
const (
IceConnectionStateNew IceConnectionState = iota
IceConnectionStateChecking
IceConnectionStateConnected
IceConnectionStateCompleted
IceConnectionStateFailed
IceConnectionStateDisconnected
IceConnectionStateClosed
)
var IceConnectionStateString = []string{
"New", "Checking", "Connected", "Completed",
"Failed", "Disconnected", "Closed"}
const (
IceGatheringStateNew IceGatheringState = iota
IceGatheringStateGathering
IceGatheringStateComplete
)
var IceGatheringStateString = []string{
"New", "Gathering", "Complete"}
/* WebRTC PeerConnection
This is the main container of WebRTC functionality - from handling the ICE
negotiation to setting up Data Channels.
See: https://w3c.github.io/webrtc-pc/#idl-def-RTCPeerConnection
*/
type PeerConnection struct {
localDescription *SessionDescription
remoteDescription *SessionDescription
canTrickleIceCandidates bool
// Event handlers
OnNegotiationNeeded func()
OnIceCandidate func(IceCandidate)
OnIceCandidateError func()
OnIceComplete func() // Possibly to be removed.
OnSignalingStateChange func(SignalingState)
OnIceConnectionStateChange func(IceConnectionState)
OnIceGatheringStateChange func(IceGatheringState)
OnConnectionStateChange func(PeerConnectionState)
OnDataChannel func(*data.Channel)
config Configuration
cgoPeer C.CGO_Peer // Native code internals
}
/* Construct a WebRTC PeerConnection.
For a successful connection, provide at least one ICE server (stun or turn)
in the |Configuration| struct.
*/
func NewPeerConnection(config *Configuration) (*PeerConnection, error) {
if nil == config {
return nil, errors.New("PeerConnection requires a Configuration.")
}
pc := new(PeerConnection)
// INFO.Println("PC at ", unsafe.Pointer(pc))
// Internal CGO Peer wraps the native webrtc::PeerConnectionInterface.
pc.cgoPeer = C.CGO_InitializePeer(unsafe.Pointer(pc))
if nil == pc.cgoPeer {
return pc, errors.New("PeerConnection: failed to initialize.")
}
pc.config = *config
cConfig := config._CGO()
if 0 != C.CGO_CreatePeerConnection(pc.cgoPeer, &cConfig) {
return nil, errors.New("PeerConnection: could not create from config.")
}
INFO.Println("Created PeerConnection: ", pc, pc.cgoPeer)
return pc, nil
}
//
// === Session Description Protocol ===
//
/*
CreateOffer prepares an SDP "offer" message, which should be set as the local
description, then sent to the remote peer over a signalling channel. This
should only be called by the peer initiating the connection.
This method is blocking, and should occur within a separate goroutine.
*/
func (pc *PeerConnection) CreateOffer() (*SessionDescription, error) {
sdp := C.CGO_CreateOffer(pc.cgoPeer)
if nil == sdp {
return nil, errors.New("CreateOffer: could not prepare SDP offer.")
}
offer := new(SessionDescription)
offer.cgoSdp = sdp
offer.Type = "offer"
offer.Sdp = C.GoString(C.CGO_SerializeSDP(sdp))
return offer, nil
}
/*
CreateAnswer prepares an SDP "answer" message. This should only happen in
response to an offer received and set as the remote description. Once generated,
this answer should then be set as the local description and sent back over the
signaling channel to the remote peer.
This method is blocking, and should occur within a separate goroutine.
*/
func (pc *PeerConnection) CreateAnswer() (*SessionDescription, error) {
sdp := C.CGO_CreateAnswer(pc.cgoPeer)
if nil == sdp {
return nil, errors.New("CreateAnswer failed: could not prepare SDP offer.")
}
answer := new(SessionDescription)
answer.cgoSdp = sdp
answer.Type = "answer"
answer.Sdp = C.GoString(C.CGO_SerializeSDP(sdp))
return answer, nil
}
/*
Set a |SessionDescription| as the local description. The description should be
generated from the local peer's CreateOffer or CreateAnswer, and not be a
description received over the signaling channel.
*/
func (pc *PeerConnection) SetLocalDescription(sdp *SessionDescription) error {
if nil == sdp {
return errors.New("Cannot use nil SessionDescription.")
}
r := C.CGO_SetLocalDescription(pc.cgoPeer, sdp.cgoSdp)
if 0 != r {
return errors.New("SetLocalDescription failed.")
}
pc.localDescription = sdp
return nil
}
// readonly localDescription
func (pc *PeerConnection) LocalDescription() (sdp *SessionDescription) {
// Refresh SDP; it might have changed by ICE candidate gathering.
pc.localDescription.Sdp = C.GoString(C.CGO_SerializeSDP(
pc.localDescription.cgoSdp))
return pc.localDescription
}
/*
Set a |SessionDescription| as the remote description. This description should
be one generated by the remote peer's CreateOffer or CreateAnswer, received
over the signaling channel, and not a description created locally.
If the local peer is the answerer, this must be called before CreateAnswer.
*/
func (pc *PeerConnection) SetRemoteDescription(sdp *SessionDescription) error {
if nil == sdp {
return errors.New("Cannot use nil SessionDescription.")
}
r := C.CGO_SetRemoteDescription(pc.cgoPeer, sdp.cgoSdp)
if 0 != r {
return errors.New("SetRemoteDescription failed.")
}
pc.remoteDescription = sdp
return nil
}
// readonly remoteDescription
func (pc *PeerConnection) RemoteDescription() (sdp *SessionDescription) {
return pc.remoteDescription
}
// readonly signalingState
func (pc *PeerConnection) SignalingState() SignalingState {
return (SignalingState)(C.CGO_GetSignalingState(pc.cgoPeer))
}
// readonly connectionState
func (pc *PeerConnection) ConnectionState() PeerConnectionState {
// TODO: Aggregate states according to:
// https://w3c.github.io/webrtc-pc/#rtcpeerconnectionstate-enum
return (PeerConnectionState)(C.CGO_IceConnectionState(pc.cgoPeer))
}
// readonly icegatheringstatee
func (pc *PeerConnection) IceGatheringState() IceGatheringState {
return (IceGatheringState)(C.CGO_IceGatheringState(pc.cgoPeer))
}
// readonly iceconnectionState
func (pc *PeerConnection) IceConnectionState() IceConnectionState {
return (IceConnectionState)(C.CGO_IceConnectionState(pc.cgoPeer))
}
func (pc *PeerConnection) AddIceCandidate(ic IceCandidate) error {
sdpMid := C.CString(ic.SdpMid)
defer C.free(unsafe.Pointer(sdpMid))
sdp := C.CString(ic.Candidate)
defer C.free(unsafe.Pointer(sdp))
cIC := new(C.CGO_IceCandidate)
cIC.sdp_mid = sdpMid
cIC.sdp_mline_index = C.int(ic.SdpMLineIndex)
cIC.sdp = sdp
r := C.CGO_AddIceCandidate(pc.cgoPeer, cIC)
if 0 != r {
return errors.New("AddIceCandidate failed.")
}
return nil
}
func (pc *PeerConnection) GetConfiguration() Configuration {
// There does not appear to be a native code version of GetConfiguration -
// so we'll keep track of it purely from Go.
return pc.config
}
func (pc *PeerConnection) SetConfiguration(config Configuration) error {
cConfig := config._CGO()
if 0 != C.CGO_SetConfiguration(pc.cgoPeer, &cConfig) {
return errors.New("PeerConnection: could not set configuration.")
}
pc.config = config
return nil
}
/*
Create and return a DataChannel.
This only needs to be called by one side, unless "negotiated" is true.
If creating the first DataChannel, this actually triggers the local
PeerConnection's .OnNegotiationNeeded callback, which should lead to a
user-provided goroutine containing CreateOffer, SetLocalDescription, and the
rest of the signalling exchange.
Once the connection succeeds, .OnDataChannel should trigger on the remote peer's
|PeerConnection|, while .OnOpen should trigger on the local DataChannel returned
by this method. Both DataChannel references should then be open and ready to
exchange data.
TODO: Implement the "negotiated" flag?
*/
func (pc *PeerConnection) CreateDataChannel(label string, dict data.Init) (
*data.Channel, error) {
l := C.CString(label)
defer C.free(unsafe.Pointer(l))
cDataChannel := C.CGO_CreateDataChannel(pc.cgoPeer, l, unsafe.Pointer(&dict))
if nil == cDataChannel {
return nil, errors.New("Failed to CreateDataChannel")
}
// Provide internal Data Channel as reference to create the Go wrapper.
dc := data.NewChannel(unsafe.Pointer(cDataChannel))
return dc, nil
}
func (pc *PeerConnection) Close() error {
C.CGO_Close(pc.cgoPeer)
return nil
}
//
// === cgo hooks for user-provided Go funcs fired from C callbacks ===
//
//export cgoOnSignalingStateChange
func cgoOnSignalingStateChange(p unsafe.Pointer, s SignalingState) {
INFO.Println("fired OnSignalingStateChange: ", p,
s, SignalingStateString[s])
pc := (*PeerConnection)(p)
if nil != pc.OnSignalingStateChange {
pc.OnSignalingStateChange(s)
}
}
//export cgoOnNegotiationNeeded
func cgoOnNegotiationNeeded(p unsafe.Pointer) {
INFO.Println("fired OnNegotiationNeeded: ", p)
pc := (*PeerConnection)(p)
if nil != pc.OnNegotiationNeeded {
pc.OnNegotiationNeeded()
}
}
//export cgoOnIceCandidate
func cgoOnIceCandidate(p unsafe.Pointer, cIC C.CGO_IceCandidate) {
ic := IceCandidate{
C.GoString(cIC.sdp),
C.GoString(cIC.sdp_mid),
int(cIC.sdp_mline_index),
}
INFO.Println("fired OnIceCandidate: ", p, ic.Candidate)
pc := (*PeerConnection)(p)
if nil != pc.OnIceCandidate {
pc.OnIceCandidate(ic)
}
}
//export cgoOnIceCandidateError
func cgoOnIceCandidateError(p unsafe.Pointer) {
INFO.Println("fired OnIceCandidateError: ", p)
pc := (*PeerConnection)(p)
if nil != pc.OnIceCandidateError {
pc.OnIceCandidateError()
}
}
//export cgoOnConnectionStateChange
func cgoOnConnectionStateChange(p unsafe.Pointer, state PeerConnectionState) {
INFO.Println("fired OnConnectionStateChange: ", p)
pc := (*PeerConnection)(p)
if nil != pc.OnConnectionStateChange {
pc.OnConnectionStateChange(state)
}
}
//export cgoOnIceConnectionStateChange
func cgoOnIceConnectionStateChange(p unsafe.Pointer, state IceConnectionState) {
INFO.Println("fired OnIceConnectionStateChange: ", p)
pc := (*PeerConnection)(p)
if nil != pc.OnIceConnectionStateChange {
pc.OnIceConnectionStateChange(state)
}
}
//export cgoOnIceGatheringStateChange
func cgoOnIceGatheringStateChange(p unsafe.Pointer, state IceGatheringState) {
INFO.Println("fired OnIceGatheringStateChange:", p)
pc := (*PeerConnection)(p)
if nil != pc.OnIceGatheringStateChange {
pc.OnIceGatheringStateChange(state)
}
// Although OnIceComplete is to be deprecated in the native API, and no longer
// part of the w3 spec, keeping it for go seems easier for the users.
if IceGatheringStateComplete == state && nil != pc.OnIceComplete {
pc.OnIceComplete()
}
}
//export cgoOnDataChannel
func cgoOnDataChannel(p unsafe.Pointer, cDC C.CGO_Channel) {
INFO.Println("fired OnDataChannel: ", p, cDC)
pc := (*PeerConnection)(p)
dc := data.NewChannel(unsafe.Pointer(cDC))
if nil != pc.OnDataChannel {
pc.OnDataChannel(dc)
}
}
// Test helpers
//
var _cgoIceConnectionStateNew = int(C.CGO_IceConnectionStateNew)
var _cgoIceConnectionStateChecking = int(C.CGO_IceConnectionStateChecking)
var _cgoIceConnectionStateConnected = int(C.CGO_IceConnectionStateConnected)
var _cgoIceConnectionStateCompleted = int(C.CGO_IceConnectionStateCompleted)
var _cgoIceConnectionStateFailed = int(C.CGO_IceConnectionStateFailed)
var _cgoIceConnectionStateDisconnected = int(C.CGO_IceConnectionStateDisconnected)
var _cgoIceConnectionStateClosed = int(C.CGO_IceConnectionStateClosed)
var _cgoIceGatheringStateNew = int(C.CGO_IceGatheringStateNew)
var _cgoIceGatheringStateGathering = int(C.CGO_IceGatheringStateGathering)
var _cgoIceGatheringStateComplete = int(C.CGO_IceGatheringStateComplete)
func cgoFakeIceCandidateError(pc *PeerConnection) {
C.CGO_fakeIceCandidateError(pc.cgoPeer)
}