From 4e92516d78360704a32456633dd1573daaa3a989 Mon Sep 17 00:00:00 2001 From: John Boiles Date: Sat, 11 Sep 2021 08:47:57 +0100 Subject: [PATCH] Reuse existing WebRTC connection if available --- src/octoprint/static/js/app/helpers.js | 1 + .../static/js/app/viewmodels/control.js | 18 +++++++++++++++++- .../static/js/app/viewmodels/settings.js | 10 +++++++++- 3 files changed, 27 insertions(+), 2 deletions(-) diff --git a/src/octoprint/static/js/app/helpers.js b/src/octoprint/static/js/app/helpers.js index e52a11c3a..6605c1a89 100644 --- a/src/octoprint/static/js/app/helpers.js +++ b/src/octoprint/static/js/app/helpers.js @@ -1686,4 +1686,5 @@ var startWebRTC = function (videoElement, streamUrl) { }); negotiateWebRTC(streamUrl); + return pc; }; diff --git a/src/octoprint/static/js/app/viewmodels/control.js b/src/octoprint/static/js/app/viewmodels/control.js index a8444ded4..690b6d3d9 100644 --- a/src/octoprint/static/js/app/viewmodels/control.js +++ b/src/octoprint/static/js/app/viewmodels/control.js @@ -43,6 +43,7 @@ $(function () { self.webcamHlsEnabled = ko.observable(false); self.webcamWebRTCEnabled = ko.observable(false); self.webcamError = ko.observable(false); + self.webRTCPeerConnection = null; self.keycontrolActive = ko.observable(false); self.keycontrolHelpActive = ko.observable(false); @@ -739,7 +740,22 @@ $(function () { self._switchToWebRTCWebcam = function () { var video = document.getElementById("webcam_webrtc"); - startWebRTC(video, self.settings.webcam_streamUrl()); + // Close any existing, disconnected connection + if ( + self.webRTCPeerConnection != null && + self.webRTCPeerConnection.connectionState != "connected" + ) { + self.webRTCPeerConnection.close(); + self.webRTCPeerConnection = null; + } + + // Open a new connection if necessary + if (self.webRTCPeerConnection == null) { + self.webRTCPeerConnection = startWebRTC( + video, + self.settings.webcam_streamUrl() + ); + } self.webcamMjpgEnabled(false); self.webcamHlsEnabled(false); diff --git a/src/octoprint/static/js/app/viewmodels/settings.js b/src/octoprint/static/js/app/viewmodels/settings.js index 5c8df6acb..fa8d8619f 100644 --- a/src/octoprint/static/js/app/viewmodels/settings.js +++ b/src/octoprint/static/js/app/viewmodels/settings.js @@ -439,6 +439,7 @@ $(function () { ); var streamType = determineWebcamStreamType(self.webcam_streamUrl()); var webcam_element; + var webrtc_peer_connection; if (streamType == "mjpg") { webcam_element = $(''); } else if (streamType == "hls") { @@ -459,7 +460,10 @@ $(function () { ); video_element = webcam_element[0]; - startWebRTC(video_element, self.webcam_streamUrl()); + webrtc_peer_connection = startWebRTC( + video_element, + self.webcam_streamUrl() + ); } else { throw "Unknown stream type " + streamType; } @@ -475,6 +479,10 @@ $(function () { message: message, onclose: function () { self.testWebcamStreamUrlBusy(false); + if (webrtc_peer_connection != null) { + webrtc_peer_connection.close(); + webrtc_peer_connection = null; + } } }); };