Skip to content

Commit e154d6e

Browse files
committed
Buffer ICE candidates
1 parent 982fde3 commit e154d6e

File tree

1 file changed

+17
-17
lines changed

1 file changed

+17
-17
lines changed

peer/conn.go

Lines changed: 17 additions & 17 deletions
Original file line numberDiff line numberDiff line change
@@ -71,7 +71,7 @@ func newWithClientOrServer(servers []webrtc.ICEServer, client bool, opts *ConnOp
7171
dcOpenChannel: make(chan *webrtc.DataChannel),
7272
dcDisconnectChannel: make(chan struct{}),
7373
dcFailedChannel: make(chan struct{}),
74-
localCandidateChannel: make(chan webrtc.ICECandidateInit),
74+
localCandidateChannel: make(chan webrtc.ICECandidateInit, 16),
7575
pendingRemoteCandidates: make([]webrtc.ICECandidateInit, 0),
7676
localSessionDescriptionChannel: make(chan webrtc.SessionDescription),
7777
remoteSessionDescriptionChannel: make(chan webrtc.SessionDescription),
@@ -281,6 +281,22 @@ func (c *Conn) negotiate() {
281281
return
282282
}
283283

284+
// The ICE transport resets when the remote description is updated.
285+
// Adding ICE candidates before this point causes a failed connection,
286+
// because the candidate would be lost.
287+
c.pendingCandidatesMutex.Lock()
288+
defer c.pendingCandidatesMutex.Unlock()
289+
for _, pendingCandidate := range c.pendingRemoteCandidates {
290+
c.opts.Logger.Debug(context.Background(), "flushing remote candidate")
291+
err := c.rtc.AddICECandidate(pendingCandidate)
292+
if err != nil {
293+
_ = c.CloseWithError(xerrors.Errorf("flush pending candidates: %w", err))
294+
return
295+
}
296+
}
297+
c.pendingCandidatesFlushed = true
298+
c.opts.Logger.Debug(context.Background(), "flushed remote candidates")
299+
284300
if !c.offerrer {
285301
answer, err := c.rtc.CreateAnswer(&webrtc.AnswerOptions{})
286302
if err != nil {
@@ -302,22 +318,6 @@ func (c *Conn) negotiate() {
302318
case c.localSessionDescriptionChannel <- answer:
303319
}
304320
}
305-
306-
// The ICE transport resets when the remote description is updated.
307-
// Adding ICE candidates before this point causes a failed connection,
308-
// because the candidate would be lost.
309-
c.pendingCandidatesMutex.Lock()
310-
defer c.pendingCandidatesMutex.Unlock()
311-
for _, pendingCandidate := range c.pendingRemoteCandidates {
312-
c.opts.Logger.Debug(context.Background(), "flushing remote candidate")
313-
err := c.rtc.AddICECandidate(pendingCandidate)
314-
if err != nil {
315-
_ = c.CloseWithError(xerrors.Errorf("flush pending candidates: %w", err))
316-
return
317-
}
318-
}
319-
c.pendingCandidatesFlushed = true
320-
c.opts.Logger.Debug(context.Background(), "flushed remote candidates")
321321
}
322322

323323
// LocalCandidate returns a channel that emits when a local candidate

0 commit comments

Comments
 (0)