forked from pion/webrtc
-
Notifications
You must be signed in to change notification settings - Fork 0
/
rtcpeerconnection.go
1354 lines (1167 loc) · 42.7 KB
/
rtcpeerconnection.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
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
// Package webrtc implements the WebRTC 1.0 as defined in W3C WebRTC specification document.
package webrtc
import (
"crypto/ecdsa"
"crypto/elliptic"
"crypto/rand"
"fmt"
"net"
"strings"
"sync"
"time"
"encoding/binary"
"github.com/pions/datachannel"
"github.com/pions/webrtc/internal/network"
"github.com/pions/webrtc/internal/sdp"
"github.com/pions/webrtc/pkg/ice"
"github.com/pions/webrtc/pkg/media"
"github.com/pions/webrtc/pkg/rtcerr"
"github.com/pions/webrtc/pkg/rtcp"
"github.com/pions/webrtc/pkg/rtp"
"github.com/pkg/errors"
)
// Unknown defines default public constant to use for "enum" like struct
// comparisons when no value was defined.
const Unknown = iota
// RTCPeerConnection represents a WebRTC connection that establishes a
// peer-to-peer communications with another RTCPeerConnection instance in a
// browser, or to another endpoint implementing the required protocols.
type RTCPeerConnection struct {
sync.RWMutex
configuration RTCConfiguration
// CurrentLocalDescription represents the local description that was
// successfully negotiated the last time the RTCPeerConnection transitioned
// into the stable state plus any local candidates that have been generated
// by the IceAgent since the offer or answer was created.
CurrentLocalDescription *RTCSessionDescription
// PendingLocalDescription represents a local description that is in the
// process of being negotiated plus any local candidates that have been
// generated by the IceAgent since the offer or answer was created. If the
// RTCPeerConnection is in the stable state, the value is null.
PendingLocalDescription *RTCSessionDescription
// CurrentRemoteDescription represents the last remote description that was
// successfully negotiated the last time the RTCPeerConnection transitioned
// into the stable state plus any remote candidates that have been supplied
// via AddIceCandidate() since the offer or answer was created.
CurrentRemoteDescription *RTCSessionDescription
// PendingRemoteDescription represents a remote description that is in the
// process of being negotiated, complete with any remote candidates that
// have been supplied via AddIceCandidate() since the offer or answer was
// created. If the RTCPeerConnection is in the stable state, the value is
// null.
PendingRemoteDescription *RTCSessionDescription
// SignalingState attribute returns the signaling state of the
// RTCPeerConnection instance.
SignalingState RTCSignalingState
// IceGatheringState attribute returns the ICE gathering state of the
// RTCPeerConnection instance.
IceGatheringState RTCIceGatheringState // FIXME NOT-USED
// IceConnectionState attribute returns the ICE connection state of the
// RTCPeerConnection instance.
// IceConnectionState RTCIceConnectionState // FIXME SWAP-FOR-THIS
IceConnectionState ice.ConnectionState // FIXME REMOVE
// ConnectionState attribute returns the connection state of the
// RTCPeerConnection instance.
ConnectionState RTCPeerConnectionState
idpLoginURL *string
isClosed bool
negotiationNeeded bool
lastOffer string
lastAnswer string
// Media
mediaEngine *MediaEngine
rtpTransceivers []*RTCRtpTransceiver
// sctpTransport
sctpTransport *RTCSctpTransport
// DataChannels
dataChannels map[uint16]*RTCDataChannel
// OnNegotiationNeeded func() // FIXME NOT-USED
// OnIceCandidate func() // FIXME NOT-USED
// OnIceCandidateError func() // FIXME NOT-USED
// OnIceGatheringStateChange func() // FIXME NOT-USED
// OnConnectionStateChange func() // FIXME NOT-USED
onSignalingStateChangeHandler func(RTCSignalingState)
onICEConnectionStateChangeHandler func(ice.ConnectionState)
onTrackHandler func(*RTCTrack)
onDataChannelHandler func(*RTCDataChannel)
// Deprecated: Internal mechanism which will be removed.
networkManager *network.Manager
}
// New creates a new RTCPeerConfiguration with the provided configuration
func New(configuration RTCConfiguration) (*RTCPeerConnection, error) {
// https://w3c.github.io/webrtc-pc/#constructor (Step #2)
// Some variables defined explicitly despite their implicit zero values to
// allow better readability to understand what is happening.
pc := RTCPeerConnection{
configuration: RTCConfiguration{
IceServers: []RTCIceServer{},
IceTransportPolicy: RTCIceTransportPolicyAll,
BundlePolicy: RTCBundlePolicyBalanced,
RtcpMuxPolicy: RTCRtcpMuxPolicyRequire,
Certificates: []RTCCertificate{},
IceCandidatePoolSize: 0,
},
isClosed: false,
negotiationNeeded: false,
lastOffer: "",
lastAnswer: "",
SignalingState: RTCSignalingStateStable,
// IceConnectionState: RTCIceConnectionStateNew, // FIXME SWAP-FOR-THIS
IceConnectionState: ice.ConnectionStateNew, // FIXME REMOVE
IceGatheringState: RTCIceGatheringStateNew,
ConnectionState: RTCPeerConnectionStateNew,
mediaEngine: DefaultMediaEngine,
sctpTransport: newRTCSctpTransport(),
dataChannels: make(map[uint16]*RTCDataChannel),
}
var err error
if err = pc.initConfiguration(configuration); err != nil {
return nil, err
}
var urls []*ice.URL
for _, server := range pc.configuration.IceServers {
for _, rawURL := range server.URLs {
var url *ice.URL
url, err = ice.ParseURL(rawURL)
if err != nil {
return nil, err
}
urls = append(urls, url)
}
}
pc.networkManager, err = network.NewManager(urls, pc.generateChannel, pc.iceStateChange, defaultSettingEngine.EphemeralUDP.PortMin, defaultSettingEngine.EphemeralUDP.PortMax)
if err != nil {
return nil, err
}
return &pc, nil
}
// initConfiguration defines validation of the specified RTCConfiguration and
// its assignment to the internal configuration variable. This function differs
// from its SetConfiguration counterpart because most of the checks do not
// include verification statements related to the existing state. Thus the
// function describes only minor verification of some the struct variables.
func (pc *RTCPeerConnection) initConfiguration(configuration RTCConfiguration) error {
if configuration.PeerIdentity != "" {
pc.configuration.PeerIdentity = configuration.PeerIdentity
}
// https://www.w3.org/TR/webrtc/#constructor (step #3)
if len(configuration.Certificates) > 0 {
now := time.Now()
for _, x509Cert := range configuration.Certificates {
if !x509Cert.Expires().IsZero() && now.After(x509Cert.Expires()) {
return &rtcerr.InvalidAccessError{Err: ErrCertificateExpired}
}
pc.configuration.Certificates = append(pc.configuration.Certificates, x509Cert)
}
} else {
sk, err := ecdsa.GenerateKey(elliptic.P256(), rand.Reader)
if err != nil {
return &rtcerr.UnknownError{Err: err}
}
certificate, err := GenerateCertificate(sk)
if err != nil {
return err
}
pc.configuration.Certificates = []RTCCertificate{*certificate}
}
if configuration.BundlePolicy != RTCBundlePolicy(Unknown) {
pc.configuration.BundlePolicy = configuration.BundlePolicy
}
if configuration.RtcpMuxPolicy != RTCRtcpMuxPolicy(Unknown) {
pc.configuration.RtcpMuxPolicy = configuration.RtcpMuxPolicy
}
if configuration.IceCandidatePoolSize != 0 {
pc.configuration.IceCandidatePoolSize = configuration.IceCandidatePoolSize
}
if configuration.IceTransportPolicy != RTCIceTransportPolicy(Unknown) {
pc.configuration.IceTransportPolicy = configuration.IceTransportPolicy
}
if len(configuration.IceServers) > 0 {
for _, server := range configuration.IceServers {
if err := server.validate(); err != nil {
return err
}
}
pc.configuration.IceServers = configuration.IceServers
}
return nil
}
// OnSignalingStateChange sets an event handler which is invoked when the
// peer connection's signaling state changes
func (pc *RTCPeerConnection) OnSignalingStateChange(f func(RTCSignalingState)) {
pc.Lock()
defer pc.Unlock()
pc.onSignalingStateChangeHandler = f
}
func (pc *RTCPeerConnection) onSignalingStateChange(newState RTCSignalingState) (done chan struct{}) {
pc.RLock()
hdlr := pc.onSignalingStateChangeHandler
pc.RUnlock()
done = make(chan struct{})
if hdlr == nil {
close(done)
return
}
go func() {
hdlr(newState)
close(done)
}()
return
}
// OnDataChannel sets an event handler which is invoked when a data
// channel message arrives from a remote peer.
func (pc *RTCPeerConnection) OnDataChannel(f func(*RTCDataChannel)) {
pc.Lock()
defer pc.Unlock()
pc.onDataChannelHandler = f
}
func (pc *RTCPeerConnection) onDataChannel(dc *RTCDataChannel) (done chan struct{}) {
pc.RLock()
hdlr := pc.onDataChannelHandler
pc.RUnlock()
done = make(chan struct{})
if hdlr == nil || dc == nil {
close(done)
return
}
// Run this synchronously to allow setup done in onDataChannelFn()
// to complete before datachannel event handlers might be called.
go func() {
hdlr(dc)
close(done)
}()
return
}
// OnTrack sets an event handler which is called when remote track
// arrives from a remote peer.
func (pc *RTCPeerConnection) OnTrack(f func(*RTCTrack)) {
pc.Lock()
defer pc.Unlock()
pc.onTrackHandler = f
}
func (pc *RTCPeerConnection) onTrack(t *RTCTrack) (done chan struct{}) {
pc.RLock()
hdlr := pc.onTrackHandler
pc.RUnlock()
done = make(chan struct{})
if hdlr == nil || t == nil {
close(done)
return
}
go func() {
hdlr(t)
close(done)
}()
return
}
// OnICEConnectionStateChange sets an event handler which is called
// when an ICE connection state is changed.
func (pc *RTCPeerConnection) OnICEConnectionStateChange(f func(ice.ConnectionState)) {
pc.Lock()
defer pc.Unlock()
pc.onICEConnectionStateChangeHandler = f
}
func (pc *RTCPeerConnection) onICEConnectionStateChange(cs ice.ConnectionState) (done chan struct{}) {
pc.RLock()
hdlr := pc.onICEConnectionStateChangeHandler
pc.RUnlock()
done = make(chan struct{})
if hdlr == nil {
close(done)
return
}
go func() {
hdlr(cs)
close(done)
}()
return
}
// SetConfiguration updates the configuration of this RTCPeerConnection object.
func (pc *RTCPeerConnection) SetConfiguration(configuration RTCConfiguration) error {
// https://www.w3.org/TR/webrtc/#dom-rtcpeerconnection-setconfiguration (step #2)
if pc.isClosed {
return &rtcerr.InvalidStateError{Err: ErrConnectionClosed}
}
// https://www.w3.org/TR/webrtc/#set-the-configuration (step #3)
if configuration.PeerIdentity != "" {
if configuration.PeerIdentity != pc.configuration.PeerIdentity {
return &rtcerr.InvalidModificationError{Err: ErrModifyingPeerIdentity}
}
pc.configuration.PeerIdentity = configuration.PeerIdentity
}
// https://www.w3.org/TR/webrtc/#set-the-configuration (step #4)
if len(configuration.Certificates) > 0 {
if len(configuration.Certificates) != len(pc.configuration.Certificates) {
return &rtcerr.InvalidModificationError{Err: ErrModifyingCertificates}
}
for i, certificate := range configuration.Certificates {
if !pc.configuration.Certificates[i].Equals(certificate) {
return &rtcerr.InvalidModificationError{Err: ErrModifyingCertificates}
}
}
pc.configuration.Certificates = configuration.Certificates
}
// https://www.w3.org/TR/webrtc/#set-the-configuration (step #5)
if configuration.BundlePolicy != RTCBundlePolicy(Unknown) {
if configuration.BundlePolicy != pc.configuration.BundlePolicy {
return &rtcerr.InvalidModificationError{Err: ErrModifyingBundlePolicy}
}
pc.configuration.BundlePolicy = configuration.BundlePolicy
}
// https://www.w3.org/TR/webrtc/#set-the-configuration (step #6)
if configuration.RtcpMuxPolicy != RTCRtcpMuxPolicy(Unknown) {
if configuration.RtcpMuxPolicy != pc.configuration.RtcpMuxPolicy {
return &rtcerr.InvalidModificationError{Err: ErrModifyingRtcpMuxPolicy}
}
pc.configuration.RtcpMuxPolicy = configuration.RtcpMuxPolicy
}
// https://www.w3.org/TR/webrtc/#set-the-configuration (step #7)
if configuration.IceCandidatePoolSize != 0 {
if pc.configuration.IceCandidatePoolSize != configuration.IceCandidatePoolSize &&
pc.LocalDescription() != nil {
return &rtcerr.InvalidModificationError{Err: ErrModifyingIceCandidatePoolSize}
}
pc.configuration.IceCandidatePoolSize = configuration.IceCandidatePoolSize
}
// https://www.w3.org/TR/webrtc/#set-the-configuration (step #8)
if configuration.IceTransportPolicy != RTCIceTransportPolicy(Unknown) {
pc.configuration.IceTransportPolicy = configuration.IceTransportPolicy
}
// https://www.w3.org/TR/webrtc/#set-the-configuration (step #11)
if len(configuration.IceServers) > 0 {
// https://www.w3.org/TR/webrtc/#set-the-configuration (step #11.3)
for _, server := range configuration.IceServers {
if err := server.validate(); err != nil {
return err
}
}
pc.configuration.IceServers = configuration.IceServers
}
return nil
}
// GetConfiguration returns an RTCConfiguration object representing the current
// configuration of this RTCPeerConnection object. The returned object is a
// copy and direct mutation on it will not take affect until SetConfiguration
// has been called with RTCConfiguration passed as its only argument.
// https://www.w3.org/TR/webrtc/#dom-rtcpeerconnection-getconfiguration
func (pc *RTCPeerConnection) GetConfiguration() RTCConfiguration {
return pc.configuration
}
// ------------------------------------------------------------------------
// --- FIXME - BELOW CODE NEEDS REVIEW/CLEANUP
// ------------------------------------------------------------------------
// CreateOffer starts the RTCPeerConnection and generates the localDescription
func (pc *RTCPeerConnection) CreateOffer(options *RTCOfferOptions) (RTCSessionDescription, error) {
useIdentity := pc.idpLoginURL != nil
if options != nil {
return RTCSessionDescription{}, errors.Errorf("TODO handle options")
} else if useIdentity {
return RTCSessionDescription{}, errors.Errorf("TODO handle identity provider")
} else if pc.isClosed {
return RTCSessionDescription{}, &rtcerr.InvalidStateError{Err: ErrConnectionClosed}
}
d := sdp.NewJSEPSessionDescription(useIdentity)
pc.addFingerprint(d)
candidates, err := pc.generateLocalCandidates()
if err != nil {
return RTCSessionDescription{}, err
}
bundleValue := "BUNDLE"
if pc.addRTPMediaSection(d, RTCRtpCodecTypeAudio, "audio", RTCRtpTransceiverDirectionSendrecv, candidates, sdp.ConnectionRoleActpass) {
bundleValue += " audio"
}
if pc.addRTPMediaSection(d, RTCRtpCodecTypeVideo, "video", RTCRtpTransceiverDirectionSendrecv, candidates, sdp.ConnectionRoleActpass) {
bundleValue += " video"
}
pc.addDataMediaSection(d, "data", candidates, sdp.ConnectionRoleActpass)
d = d.WithValueAttribute(sdp.AttrKeyGroup, bundleValue+" data")
for _, m := range d.MediaDescriptions {
m.WithPropertyAttribute("setup:actpass")
}
desc := RTCSessionDescription{
Type: RTCSdpTypeOffer,
Sdp: d.Marshal(),
parsed: d,
}
pc.lastOffer = desc.Sdp
// FIXME: This doesn't follow the JS API spec, but removing it
// would mean our examples and existing code have to change
if err := pc.SetLocalDescription(desc); err != nil {
return RTCSessionDescription{}, err
}
return desc, nil
}
// CreateAnswer starts the RTCPeerConnection and generates the localDescription
func (pc *RTCPeerConnection) CreateAnswer(options *RTCAnswerOptions) (RTCSessionDescription, error) {
useIdentity := pc.idpLoginURL != nil
if options != nil {
return RTCSessionDescription{}, errors.Errorf("TODO handle options")
} else if useIdentity {
return RTCSessionDescription{}, errors.Errorf("TODO handle identity provider")
} else if pc.isClosed {
return RTCSessionDescription{}, &rtcerr.InvalidStateError{Err: ErrConnectionClosed}
}
candidates, err := pc.generateLocalCandidates()
if err != nil {
return RTCSessionDescription{}, err
}
d := sdp.NewJSEPSessionDescription(useIdentity)
pc.addFingerprint(d)
bundleValue := "BUNDLE"
for _, remoteMedia := range pc.RemoteDescription().parsed.MediaDescriptions {
// TODO @trivigy better SDP parser
var peerDirection RTCRtpTransceiverDirection
midValue := ""
for _, a := range remoteMedia.Attributes {
if strings.HasPrefix(*a.String(), "mid") {
midValue = (*a.String())[len("mid:"):]
} else if strings.HasPrefix(*a.String(), "sendrecv") {
peerDirection = RTCRtpTransceiverDirectionSendrecv
} else if strings.HasPrefix(*a.String(), "sendonly") {
peerDirection = RTCRtpTransceiverDirectionSendonly
} else if strings.HasPrefix(*a.String(), "recvonly") {
peerDirection = RTCRtpTransceiverDirectionRecvonly
}
}
appendBundle := func() {
bundleValue += " " + midValue
}
if strings.HasPrefix(*remoteMedia.MediaName.String(), "audio") {
if pc.addRTPMediaSection(d, RTCRtpCodecTypeAudio, midValue, peerDirection, candidates, sdp.ConnectionRoleActive) {
appendBundle()
}
} else if strings.HasPrefix(*remoteMedia.MediaName.String(), "video") {
if pc.addRTPMediaSection(d, RTCRtpCodecTypeVideo, midValue, peerDirection, candidates, sdp.ConnectionRoleActive) {
appendBundle()
}
} else if strings.HasPrefix(*remoteMedia.MediaName.String(), "application") {
pc.addDataMediaSection(d, midValue, candidates, sdp.ConnectionRoleActive)
appendBundle()
}
}
d = d.WithValueAttribute(sdp.AttrKeyGroup, bundleValue)
desc := RTCSessionDescription{
Type: RTCSdpTypeAnswer,
Sdp: d.Marshal(),
parsed: d,
}
pc.lastAnswer = desc.Sdp
// FIXME: This doesn't follow the JS API spec, but removing it
// would mean our examples and existing code have to change
if err := pc.SetLocalDescription(desc); err != nil {
return RTCSessionDescription{}, err
}
return desc, nil
}
// 4.4.1.6 Set the RTCSessionDescription
func (pc *RTCPeerConnection) setDescription(sd *RTCSessionDescription, op rtcStateChangeOp) error {
if pc.isClosed {
return &rtcerr.InvalidStateError{Err: ErrConnectionClosed}
}
cur := pc.SignalingState
setLocal := rtcStateChangeOpSetLocal
setRemote := rtcStateChangeOpSetRemote
newSdpDoesNotMatchOffer := &rtcerr.InvalidModificationError{Err: errors.New("New sdp does not match previous offer")}
newSdpDoesNotMatchAnswer := &rtcerr.InvalidModificationError{Err: errors.New("New sdp does not match previous answer")}
var nextState RTCSignalingState
var err error
switch op {
case setLocal:
switch sd.Type {
// stable->SetLocal(offer)->have-local-offer
case RTCSdpTypeOffer:
if sd.Sdp != pc.lastOffer {
return newSdpDoesNotMatchOffer
}
nextState, err = checkNextSignalingState(cur, RTCSignalingStateHaveLocalOffer, setLocal, sd.Type)
if err == nil {
pc.PendingLocalDescription = sd
}
// have-remote-offer->SetLocal(answer)->stable
// have-local-pranswer->SetLocal(answer)->stable
case RTCSdpTypeAnswer:
if sd.Sdp != pc.lastAnswer {
return newSdpDoesNotMatchAnswer
}
nextState, err = checkNextSignalingState(cur, RTCSignalingStateStable, setLocal, sd.Type)
if err == nil {
pc.CurrentLocalDescription = sd
pc.CurrentRemoteDescription = pc.PendingRemoteDescription
pc.PendingRemoteDescription = nil
pc.PendingLocalDescription = nil
}
case RTCSdpTypeRollback:
nextState, err = checkNextSignalingState(cur, RTCSignalingStateStable, setLocal, sd.Type)
if err == nil {
pc.PendingLocalDescription = nil
}
// have-remote-offer->SetLocal(pranswer)->have-local-pranswer
case RTCSdpTypePranswer:
if sd.Sdp != pc.lastAnswer {
return newSdpDoesNotMatchAnswer
}
nextState, err = checkNextSignalingState(cur, RTCSignalingStateHaveLocalPranswer, setLocal, sd.Type)
if err == nil {
pc.PendingLocalDescription = sd
}
default:
return &rtcerr.OperationError{Err: fmt.Errorf("Invalid state change op: %s(%s)", op, sd.Type)}
}
case setRemote:
switch sd.Type {
// stable->SetRemote(offer)->have-remote-offer
case RTCSdpTypeOffer:
nextState, err = checkNextSignalingState(cur, RTCSignalingStateHaveRemoteOffer, setRemote, sd.Type)
if err == nil {
pc.PendingRemoteDescription = sd
}
// have-local-offer->SetRemote(answer)->stable
// have-remote-pranswer->SetRemote(answer)->stable
case RTCSdpTypeAnswer:
nextState, err = checkNextSignalingState(cur, RTCSignalingStateStable, setRemote, sd.Type)
if err == nil {
pc.CurrentRemoteDescription = sd
pc.CurrentLocalDescription = pc.PendingLocalDescription
pc.PendingRemoteDescription = nil
pc.PendingLocalDescription = nil
}
case RTCSdpTypeRollback:
nextState, err = checkNextSignalingState(cur, RTCSignalingStateStable, setRemote, sd.Type)
if err == nil {
pc.PendingRemoteDescription = nil
}
// have-local-offer->SetRemote(pranswer)->have-remote-pranswer
case RTCSdpTypePranswer:
nextState, err = checkNextSignalingState(cur, RTCSignalingStateHaveRemotePranswer, setRemote, sd.Type)
if err == nil {
pc.PendingRemoteDescription = sd
}
default:
return &rtcerr.OperationError{Err: fmt.Errorf("Invalid state change op: %s(%s)", op, sd.Type)}
}
default:
return &rtcerr.OperationError{Err: fmt.Errorf("Unhandled state change op: %q", op)}
}
if err == nil {
pc.SignalingState = nextState
pc.onSignalingStateChange(nextState)
}
return err
}
// SetLocalDescription sets the SessionDescription of the local peer
func (pc *RTCPeerConnection) SetLocalDescription(desc RTCSessionDescription) error {
if pc.isClosed {
return &rtcerr.InvalidStateError{Err: ErrConnectionClosed}
}
// JSEP 5.4
if desc.Sdp == "" {
switch desc.Type {
case RTCSdpTypeAnswer, RTCSdpTypePranswer:
desc.Sdp = pc.lastAnswer
case RTCSdpTypeOffer:
desc.Sdp = pc.lastOffer
default:
return &rtcerr.InvalidModificationError{
Err: fmt.Errorf("Invalid SDP type supplied to SetLocalDescription(): %s", desc.Type),
}
}
}
// TODO: Initiate ICE candidate gathering?
desc.parsed = &sdp.SessionDescription{}
if err := desc.parsed.Unmarshal(desc.Sdp); err != nil {
return err
}
return pc.setDescription(&desc, rtcStateChangeOpSetLocal)
}
// LocalDescription returns PendingLocalDescription if it is not null and
// otherwise it returns CurrentLocalDescription. This property is used to
// determine if setLocalDescription has already been called.
// https://www.w3.org/TR/webrtc/#dom-rtcpeerconnection-localdescription
func (pc *RTCPeerConnection) LocalDescription() *RTCSessionDescription {
if pc.PendingLocalDescription != nil {
return pc.PendingLocalDescription
}
return pc.CurrentLocalDescription
}
// SetRemoteDescription sets the SessionDescription of the remote peer
func (pc *RTCPeerConnection) SetRemoteDescription(desc RTCSessionDescription) error {
// FIXME: Remove this when renegotiation is supported
if pc.CurrentRemoteDescription != nil {
return errors.Errorf("remoteDescription is already defined, SetRemoteDescription can only be called once")
}
if pc.isClosed {
return &rtcerr.InvalidStateError{Err: ErrConnectionClosed}
}
desc.parsed = &sdp.SessionDescription{}
if err := desc.parsed.Unmarshal(desc.Sdp); err != nil {
return err
}
if err := pc.setDescription(&desc, rtcStateChangeOpSetRemote); err != nil {
return err
}
weOffer := true
remoteUfrag := ""
remotePwd := ""
if desc.Type == RTCSdpTypeOffer {
weOffer = false
}
for _, m := range pc.RemoteDescription().parsed.MediaDescriptions {
for _, a := range m.Attributes {
if strings.HasPrefix(*a.String(), "candidate") {
c, err := sdp.ICECandidateUnmarshal(*a.String())
if err != nil {
return err
}
if err := pc.networkManager.IceAgent.AddRemoteCandidate(c); err != nil {
return err
}
} else if strings.HasPrefix(*a.String(), "ice-ufrag") {
remoteUfrag = (*a.String())[len("ice-ufrag:"):]
} else if strings.HasPrefix(*a.String(), "ice-pwd") {
remotePwd = (*a.String())[len("ice-pwd:"):]
}
}
}
fingerprint, ok := desc.parsed.Attribute("fingerprint")
if !ok {
fingerprint, ok = desc.parsed.MediaDescriptions[0].Attribute("fingerprint")
if !ok {
return errors.New("could not find fingerprint")
}
}
var fingerprintHash string
parts := strings.Split(fingerprint, " ")
if len(parts) != 2 {
return errors.New("invalid fingerprint")
}
fingerprint = parts[1]
fingerprintHash = parts[0]
go func() {
cert := pc.configuration.Certificates[0] // TODO: handle multiple certs
err := pc.networkManager.Start(weOffer,
remoteUfrag, remotePwd,
cert.x509Cert, cert.privateKey, fingerprint, fingerprintHash)
if err != nil {
fmt.Println("Failed to start manager", err)
}
// Temporary data channel glue
pc.openDataChannels()
pc.acceptDataChannels()
}()
return nil
}
// openDataChannels opens the existing data channels
// TODO: Move to RTCDataChannel
func (pc *RTCPeerConnection) openDataChannels() {
pc.RLock()
defer pc.RUnlock()
for _, rtcDC := range pc.dataChannels {
dc, err := pc.networkManager.OpenDataChannel(
*rtcDC.ID,
&datachannel.Config{
ChannelType: datachannel.ChannelTypeReliable, // TODO: Wiring
Priority: datachannel.ChannelPriorityNormal, // TODO: Wiring
ReliabilityParameter: 0, // TODO: Wiring
Label: rtcDC.Label,
})
if err != nil {
fmt.Println("failed to open data channel", err)
continue
}
rtcDC.ReadyState = RTCDataChannelStateOpen
rtcDC.handleOpen(dc)
}
}
// acceptDataChannels accepts data channels
// TODO: Move to RTCSctpTransport
func (pc *RTCPeerConnection) acceptDataChannels() {
for {
dc, err := pc.networkManager.AcceptDataChannel()
if err != nil {
fmt.Println("Failed to accept data channel:", err)
// TODO: Kill DataChannel/PeerConnection?
return
}
sid := dc.StreamIdentifier()
rtcDC := &RTCDataChannel{
ID: &sid,
Label: dc.Config.Label,
rtcPeerConnection: pc,
ReadyState: RTCDataChannelStateOpen,
}
pc.Lock()
pc.dataChannels[sid] = rtcDC
pc.Unlock()
<-pc.onDataChannel(rtcDC)
rtcDC.handleOpen(dc)
}
}
// RemoteDescription returns PendingRemoteDescription if it is not null and
// otherwise it returns CurrentRemoteDescription. This property is used to
// determine if setRemoteDescription has already been called.
// https://www.w3.org/TR/webrtc/#dom-rtcpeerconnection-remotedescription
func (pc *RTCPeerConnection) RemoteDescription() *RTCSessionDescription {
if pc.PendingRemoteDescription != nil {
return pc.PendingRemoteDescription
}
return pc.CurrentRemoteDescription
}
// AddIceCandidate accepts an ICE candidate string and adds it
// to the existing set of candidates
func (pc *RTCPeerConnection) AddIceCandidate(s string) error {
c, err := sdp.ICECandidateUnmarshal(s)
if err != nil {
return err
}
return pc.networkManager.IceAgent.AddRemoteCandidate(c)
}
// ------------------------------------------------------------------------
// --- FIXME - BELOW CODE NEEDS RE-ORGANIZATION - https://w3c.github.io/webrtc-pc/#rtp-media-api
// ------------------------------------------------------------------------
// GetSenders returns the RTCRtpSender that are currently attached to this RTCPeerConnection
func (pc *RTCPeerConnection) GetSenders() []RTCRtpSender {
result := make([]RTCRtpSender, len(pc.rtpTransceivers))
for i, tranceiver := range pc.rtpTransceivers {
result[i] = *tranceiver.Sender
}
return result
}
// GetReceivers returns the RTCRtpReceivers that are currently attached to this RTCPeerConnection
func (pc *RTCPeerConnection) GetReceivers() []RTCRtpReceiver {
result := make([]RTCRtpReceiver, len(pc.rtpTransceivers))
for i, tranceiver := range pc.rtpTransceivers {
result[i] = *tranceiver.Receiver
}
return result
}
// GetTransceivers returns the RTCRtpTransceiver that are currently attached to this RTCPeerConnection
func (pc *RTCPeerConnection) GetTransceivers() []RTCRtpTransceiver {
result := make([]RTCRtpTransceiver, len(pc.rtpTransceivers))
for i, tranceiver := range pc.rtpTransceivers {
result[i] = *tranceiver
}
return result
}
// AddTrack adds a RTCTrack to the RTCPeerConnection
func (pc *RTCPeerConnection) AddTrack(track *RTCTrack) (*RTCRtpSender, error) {
if pc.isClosed {
return nil, &rtcerr.InvalidStateError{Err: ErrConnectionClosed}
}
for _, transceiver := range pc.rtpTransceivers {
if transceiver.Sender.Track == nil {
continue
}
if track.ID == transceiver.Sender.Track.ID {
return nil, &rtcerr.InvalidAccessError{Err: ErrExistingTrack}
}
}
var transceiver *RTCRtpTransceiver
for _, t := range pc.rtpTransceivers {
if !t.stopped &&
// t.Sender == nil && // TODO: check that the sender has never sent
t.Sender.Track == nil &&
t.Receiver.Track != nil &&
t.Receiver.Track.Kind == track.Kind {
transceiver = t
break
}
}
if transceiver != nil {
if err := transceiver.setSendingTrack(track); err != nil {
return nil, err
}
} else {
var receiver *RTCRtpReceiver
sender := newRTCRtpSender(track)
transceiver = pc.newRTCRtpTransceiver(
receiver,
sender,
RTCRtpTransceiverDirectionSendonly,
)
}
transceiver.Mid = track.Kind.String() // TODO: Mid generation
return transceiver.Sender, nil
}
// func (pc *RTCPeerConnection) RemoveTrack() {
// panic("not implemented yet") // FIXME NOT-IMPLEMENTED nolint
// }
// func (pc *RTCPeerConnection) AddTransceiver() RTCRtpTransceiver {
// panic("not implemented yet") // FIXME NOT-IMPLEMENTED nolint
// }
// ------------------------------------------------------------------------
// --- FIXME - BELOW CODE NEEDS RE-ORGANIZATION - https://w3c.github.io/webrtc-pc/#peer-to-peer-data-api
// ------------------------------------------------------------------------
// CreateDataChannel creates a new RTCDataChannel object with the given label
// and optitional RTCDataChannelInit used to configure properties of the
// underlying channel such as data reliability.
func (pc *RTCPeerConnection) CreateDataChannel(label string, options *RTCDataChannelInit) (*RTCDataChannel, error) {
// https://w3c.github.io/webrtc-pc/#peer-to-peer-data-api (Step #2)
if pc.isClosed {
return nil, &rtcerr.InvalidStateError{Err: ErrConnectionClosed}
}
// https://w3c.github.io/webrtc-pc/#peer-to-peer-data-api (Step #5)
if len(label) > 65535 {
return nil, &rtcerr.TypeError{Err: ErrStringSizeLimit}
}
// https://w3c.github.io/webrtc-pc/#peer-to-peer-data-api (Step #3)
// Some variables defined explicitly despite their implicit zero values to
// allow better readability to understand what is happening. Additionally,
// some members are set to a non zero value default due to the default
// definitions in https://w3c.github.io/webrtc-pc/#dom-rtcdatachannelinit
// which are later overwriten by the options if any were specified.
channel := RTCDataChannel{
rtcPeerConnection: pc,
// https://w3c.github.io/webrtc-pc/#peer-to-peer-data-api (Step #4)
Label: label,
Ordered: true,
MaxPacketLifeTime: nil,
MaxRetransmits: nil,
Protocol: "",
Negotiated: false,
ID: nil,
Priority: RTCPriorityTypeLow,
// https://w3c.github.io/webrtc-pc/#dfn-create-an-rtcdatachannel (Step #2)
ReadyState: RTCDataChannelStateConnecting,
// https://w3c.github.io/webrtc-pc/#dfn-create-an-rtcdatachannel (Step #3)
BufferedAmount: 0,
}
if options != nil {
// https://w3c.github.io/webrtc-pc/#peer-to-peer-data-api (Step #7)
if options.MaxPacketLifeTime != nil {
channel.MaxPacketLifeTime = options.MaxPacketLifeTime
}
// https://w3c.github.io/webrtc-pc/#peer-to-peer-data-api (Step #8)
if options.MaxRetransmits != nil {
channel.MaxRetransmits = options.MaxRetransmits
}
// https://w3c.github.io/webrtc-pc/#peer-to-peer-data-api (Step #9)
if options.Ordered != nil {
channel.Ordered = *options.Ordered
}
// https://w3c.github.io/webrtc-pc/#peer-to-peer-data-api (Step #10)
if options.Protocol != nil {
channel.Protocol = *options.Protocol
}
// https://w3c.github.io/webrtc-pc/#peer-to-peer-da ta-api (Step #12)
if options.Negotiated != nil {
channel.Negotiated = *options.Negotiated
}
// https://w3c.github.io/webrtc-pc/#peer-to-peer-data-api (Step #13)
if options.ID != nil && channel.Negotiated {
channel.ID = options.ID
}
// https://w3c.github.io/webrtc-pc/#peer-to-peer-data-api (Step #15)
if options.Priority != nil {
channel.Priority = *options.Priority
}
}
// https://w3c.github.io/webrtc-pc/#peer-to-peer-data-api (Step #11)
if len(channel.Protocol) > 65535 {
return nil, &rtcerr.TypeError{Err: ErrStringSizeLimit}
}
// https://w3c.github.io/webrtc-pc/#peer-to-peer-data-api (Step #14)
if channel.Negotiated && channel.ID == nil {
return nil, &rtcerr.TypeError{Err: ErrNegotiatedWithoutID}
}
// https://w3c.github.io/webrtc-pc/#peer-to-peer-data-api (Step #16)
if channel.MaxPacketLifeTime != nil && channel.MaxRetransmits != nil {