diff --git a/relay.go b/relay.go index a2ce897..51c9f13 100644 --- a/relay.go +++ b/relay.go @@ -202,7 +202,7 @@ func newCall(mainOffer receivedSignal, r activeRelay) { // Enable trickling s := webrtc.SettingEngine{} - s.SetTrickle(true) + s.SetTrickle(false) // Create the API object with the MediaEngine api := webrtc.NewAPI(webrtc.WithMediaEngine(mediaEngine), @@ -403,6 +403,10 @@ func newCall(mainOffer receivedSignal, r activeRelay) { val.Close() } + // Ice candidates mutex + var newCandidatesMux sync.Mutex + newPendingCandidates := make([]*webrtc.ICECandidate, 0) + // Create new peer connection newPeerConnection, err := api.NewPeerConnection(peerConnectionConfig) if err != nil { @@ -411,6 +415,27 @@ func newCall(mainOffer receivedSignal, r activeRelay) { } clients[newMessage.peerID] = newPeerConnection + // Send ice candidates + newPeerConnection.OnICECandidate(func(c *webrtc.ICECandidate) { + if c == nil || r.closed { + return + } + + newCandidatesMux.Lock() + defer newCandidatesMux.Unlock() + + // Check if we have already determined remote descprition + desc := newPeerConnection.LocalDescription() + if desc == nil { + // Append signal to the queue + newPendingCandidates = append(newPendingCandidates, c) + } else { + // Send the signal immedialy + sendSignal(r.callHash, newMessage.peerID, c.ToJSON()) + } + + }) + // Add tracks for _, value := range localTracks { _, err = newPeerConnection.AddTrack(value) @@ -433,17 +458,16 @@ func newCall(mainOffer receivedSignal, r activeRelay) { continue } - // Send ice candidates - newPeerConnection.OnICECandidate(func(c *webrtc.ICECandidate) { - if c != nil { - println("new ice candidate 2") - sendSignal(r.callHash, newMessage.peerID, c.ToJSON()) - } - }) - // Send offer sendSignal(r.callHash, newMessage.peerID, offer) + // Send pending ice candidates + newCandidatesMux.Lock() + for _, c := range newPendingCandidates { + sendSignal(r.callHash, newMessage.peerID, c.ToJSON()) + } + newCandidatesMux.Unlock() + } else if newMessage.sigType == SDP { // Got an answer from the client