Skip to content

Commit

Permalink
webrtc: fix connection in case of high latency
Browse files Browse the repository at this point in the history
When latency is high, one side of the peer connection switched to the
"connected" state before the other one, and then closed the WebSocket
connection since it's useless after the peer connection has been
established. This caused the other side of the connection to detect a
WebSocket error and to exit.

The WebSocket connection must remain open, otherwise the
"connected" state is not set by both parts.
  • Loading branch information
aler9 committed Dec 20, 2022
1 parent 7a5c426 commit bab5cae
Show file tree
Hide file tree
Showing 2 changed files with 14 additions and 5 deletions.
13 changes: 10 additions & 3 deletions internal/core/webrtc_conn.go
Original file line number Diff line number Diff line change
Expand Up @@ -30,6 +30,10 @@ import (
"github.com/aler9/rtsp-simple-server/internal/logger"
)

const (
handshakeDeadline = 10 * time.Second
)

type webRTCTrack struct {
media *media.Media
format format.Format
Expand Down Expand Up @@ -205,8 +209,8 @@ func (c *webRTCConn) runInner(ctx context.Context) error {
}

// maximum deadline to complete the handshake
c.wsconn.SetReadDeadline(time.Now().Add(10 * time.Second))
c.wsconn.SetWriteDeadline(time.Now().Add(10 * time.Second))
c.wsconn.SetReadDeadline(time.Now().Add(handshakeDeadline))
c.wsconn.SetWriteDeadline(time.Now().Add(handshakeDeadline))

err = c.writeICEServers(c.genICEServers())
if err != nil {
Expand Down Expand Up @@ -340,8 +344,11 @@ outer:
}
}

// do NOT close the WebSocket connection
// in order to allow the other side of the connection
// o switch to the "connected" state before WebSocket is closed.

c.log(logger.Info, "peer connection established")
c.wsconn.Close()

ringBuffer, _ := ringbuffer.New(uint64(c.readBufferCount))
defer ringBuffer.Close()
Expand Down
6 changes: 4 additions & 2 deletions internal/core/webrtc_index.html
Original file line number Diff line number Diff line change
Expand Up @@ -81,9 +81,11 @@
case "connected":
this.pc.onicecandidate = undefined;
this.ws.onmessage = undefined;
this.ws.onerror = undefined
this.ws.onclose = undefined;
this.ws.close();
this.ws = null;
// do not close the WebSocket connection
// in order to allow the other side of the connection
// to switch to the "connected" state before WebSocket is closed.
break;

case "disconnected":
Expand Down

0 comments on commit bab5cae

Please sign in to comment.