diff --git a/src/octoprint/__init__.py b/src/octoprint/__init__.py
index 32fa2f3c6..b67212f64 100644
--- a/src/octoprint/__init__.py
+++ b/src/octoprint/__init__.py
@@ -506,6 +506,42 @@ def init_settings_plugin_config_migration_and_cleanup(plugin_manager):
]
+def init_webcam_compat_overlay(settings, plugin_manager):
+ import logging
+
+ import octoprint.webcams
+
+ def set_overlay():
+ default_webcam = octoprint.webcams.get_default_webcam(
+ settings=settings, plugin_manager=plugin_manager
+ )
+ if default_webcam is None:
+ settings.remove_overlay("webcam_compat")
+ return
+
+ if not default_webcam.config or not default_webcam.config.compat:
+ settings.remove_overlay("webcam_compat")
+ return
+
+ logging.getLogger(__name__).info(
+ f"Installing webcam compat overlay for configured default webcam {default_webcam}"
+ )
+ overlay = {"webcam": default_webcam.config.compat.dict(by_alias=True)}
+ settings.add_overlay(
+ overlay,
+ key="webcam_compat",
+ at_end=True,
+ deprecated="Please use the webcam system introduced with 1.9.0, this compatibility layer will be removed in a future release.",
+ replace=True,
+ )
+
+ def callback(path, current_value, new_value):
+ set_overlay()
+
+ set_overlay()
+ settings.add_path_update_callback(["webcam", "defaultWebcam"], callback)
+
+
def init_custom_events(plugin_manager):
import logging
diff --git a/src/octoprint/cli/__init__.py b/src/octoprint/cli/__init__.py
index 2a7025710..91a57b79a 100644
--- a/src/octoprint/cli/__init__.py
+++ b/src/octoprint/cli/__init__.py
@@ -53,6 +53,7 @@ def init_platform_for_cli(ctx):
init_custom_events,
init_platform,
init_settings_plugin_config_migration_and_cleanup,
+ init_webcam_compat_overlay,
)
from octoprint import octoprint_plugin_inject_factory as opif
from octoprint import settings_plugin_inject_factory as spif
@@ -94,6 +95,7 @@ def init_platform_for_cli(ctx):
plugin_manager.initialize_implementations()
init_settings_plugin_config_migration_and_cleanup(plugin_manager)
+ init_webcam_compat_overlay(settings, plugin_manager)
return components
diff --git a/src/octoprint/plugin/__init__.py b/src/octoprint/plugin/__init__.py
index 2eed36694..41b5359f2 100644
--- a/src/octoprint/plugin/__init__.py
+++ b/src/octoprint/plugin/__init__.py
@@ -212,6 +212,7 @@ def call_plugin(
error_callback=None,
sorting_context=None,
initialized=True,
+ manager=None,
):
"""
Helper method to invoke the indicated ``method`` on all registered plugin implementations implementing the
@@ -249,6 +250,7 @@ def call_plugin(
Will be called with the three arguments ``name``, ``plugin`` and ``exc``. ``name`` will be the plugin
identifier, ``plugin`` the plugin implementation instance itself and ``exc`` the caught exception.
initialized (boolean): Ignored.
+ manager (PluginManager or None): The plugin manager to use. If not provided, the global plugin manager
"""
if not isinstance(types, (list, tuple)):
@@ -257,12 +259,12 @@ def call_plugin(
args = []
if kwargs is None:
kwargs = {}
+ if manager is None:
+ manager = plugin_manager()
logger = logging.getLogger(__name__)
- plugins = plugin_manager().get_implementations(
- *types, sorting_context=sorting_context
- )
+ plugins = manager.get_implementations(*types, sorting_context=sorting_context)
for plugin in plugins:
if not hasattr(plugin, "_identifier"):
continue
diff --git a/src/octoprint/plugin/types.py b/src/octoprint/plugin/types.py
index 160535df0..80d412f87 100644
--- a/src/octoprint/plugin/types.py
+++ b/src/octoprint/plugin/types.py
@@ -2319,3 +2319,30 @@ class ProgressPlugin(OctoPrintPlugin):
:param int progress: Current progress as a value between 0 and 100
"""
pass
+
+
+class WebcamProviderPlugin(OctoPrintPlugin):
+ """
+ The ``WebcamProviderPlugin`` can be used to provide one or more webcams visible on the frontend and used for snapshots/timelapses.
+ """
+
+ def get_webcam_configurations(self):
+ """
+ Used to retrieve a list of available webcams
+
+ Returns:
+ A list of :class:`~octoprint.schema.webcam.Webcam`: The available webcams, can be empty if none available.
+ """
+
+ return []
+
+ def take_webcam_snapshot(self, webcamName):
+ """
+ Used to take a JPEG snapshot of the webcam. This method may raise an exception, you can expect failures to be handled.
+
+ :param string webcamName: The name of the webcam to take a snapshot of as given by the configurations
+
+ Returns:
+ An iterator over bytes of the JPEG image
+ """
+ raise NotImplementedError()
diff --git a/src/octoprint/plugins/classicwebcam/__init__.py b/src/octoprint/plugins/classicwebcam/__init__.py
new file mode 100644
index 000000000..048fde57b
--- /dev/null
+++ b/src/octoprint/plugins/classicwebcam/__init__.py
@@ -0,0 +1,248 @@
+__license__ = "GNU Affero General Public License http://www.gnu.org/licenses/agpl.html"
+__copyright__ = "Copyright (C) 2022 The OctoPrint Project - Released under terms of the AGPLv3 License"
+
+import threading
+
+import requests
+from flask_babel import gettext
+
+import octoprint.plugin
+from octoprint.schema.webcam import RatioEnum, Webcam, WebcamCompatibility
+from octoprint.webcams import WebcamNotAbleToTakeSnapshotException
+
+
+class ClassicWebcamPlugin(
+ octoprint.plugin.AssetPlugin,
+ octoprint.plugin.TemplatePlugin,
+ octoprint.plugin.SettingsPlugin,
+ octoprint.plugin.WebcamProviderPlugin,
+ octoprint.plugin.WizardPlugin,
+):
+ def __init__(self):
+ self._capture_mutex = threading.Lock()
+ self._webcam_name = "classic"
+
+ # ~~ TemplatePlugin API
+
+ def get_assets(self):
+ return {
+ "js": [
+ "js/classicwebcam.js",
+ "js/classicwebcam_settings.js",
+ "js/classicwebcam_wizard.js",
+ ],
+ "less": ["less/classicwebcam.less"],
+ "css": ["css/classicwebcam.css"],
+ }
+
+ def get_template_configs(self):
+ return [
+ {
+ "type": "settings",
+ "template": "classicwebcam_settings.jinja2",
+ "custom_bindings": True,
+ },
+ {
+ "type": "webcam",
+ "name": "Classic Webcam",
+ "template": "classicwebcam_webcam.jinja2",
+ "custom_bindings": True,
+ "suffix": "_real",
+ },
+ {
+ "type": "wizard",
+ "name": "Classic Webcam Wizard",
+ "template": "classicwebcam_wizard.jinja2",
+ "suffix": "_wizard",
+ },
+ ]
+
+ # ~~ WebcamProviderPlugin API
+
+ def get_webcam_configurations(self):
+ streamRatio = self._settings.get(["streamRatio"])
+ if streamRatio == "4:3":
+ streamRatio = RatioEnum.four_three
+ else:
+ streamRatio = RatioEnum.sixteen_nine
+ webRtcServers = self._settings.get(["streamWebrtcIceServers"])
+ cacheBuster = self._settings.get_boolean(["cacheBuster"])
+ stream = self._get_stream_url()
+ snapshot = self._get_snapshot_url()
+ flipH = self._settings.get_boolean(["flipH"])
+ flipV = self._settings.get_boolean(["flipV"])
+ rotate90 = self._settings.get_boolean(["rotate90"])
+ snapshotSslValidation = self._settings.get_boolean(["snapshotSslValidation"])
+
+ try:
+ streamTimeout = int(self._settings.get(["streamTimeout"]))
+ except Exception:
+ streamTimeout = 5
+
+ try:
+ snapshotTimeout = int(self._settings.get(["snapshotTimeout"]))
+ except Exception:
+ snapshotTimeout = 5
+
+ return [
+ Webcam(
+ name=self._webcam_name,
+ displayName="Classic Webcam",
+ flipH=flipH,
+ flipV=flipV,
+ rotate90=rotate90,
+ snapshotDisplay=snapshot,
+ canSnapshot=self._can_snapshot(),
+ compat=WebcamCompatibility(
+ stream=stream,
+ streamTimeout=streamTimeout,
+ streamRatio=streamRatio,
+ cacheBuster=cacheBuster,
+ streamWebrtcIceServers=webRtcServers,
+ snapshot=snapshot,
+ snapshotTimeout=snapshotTimeout,
+ snapshotSslValidation=snapshotSslValidation,
+ ),
+ extras=dict(
+ stream=stream,
+ streamTimeout=streamTimeout,
+ streamRatio=streamRatio,
+ streamWebrtcIceServers=webRtcServers,
+ cacheBuster=cacheBuster,
+ ),
+ ),
+ ]
+
+ def _get_snapshot_url(self):
+ return self._settings.get(["snapshot"])
+
+ def _get_stream_url(self):
+ return self._settings.get(["stream"])
+
+ def _can_snapshot(self):
+ snapshot = self._get_snapshot_url()
+ return snapshot is not None and snapshot.strip() != ""
+
+ def take_webcam_snapshot(self, _):
+ snapshot_url = self._get_snapshot_url()
+ if not self._can_snapshot():
+ raise WebcamNotAbleToTakeSnapshotException(self._webcam_name)
+
+ with self._capture_mutex:
+ self._logger.debug(f"Capturing image from {snapshot_url}")
+ r = requests.get(
+ snapshot_url,
+ stream=True,
+ timeout=self._settings.get_int(["snapshotTimeout"]),
+ verify=self._settings.get_boolean(["rosnapshotSslValidationtate90"]),
+ )
+ r.raise_for_status()
+ return r.iter_content(chunk_size=1024)
+
+ # ~~ SettingsPlugin API
+
+ def get_settings_defaults(self):
+ return dict(
+ flipH=False,
+ flipV=False,
+ rotate90=False,
+ stream="",
+ streamTimeout=5,
+ streamRatio="16:9",
+ streamWebrtcIceServers=["stun:stun.l.google.com:19302"],
+ snapshot="",
+ cacheBuster=False,
+ snapshotSslValidation=True,
+ snapshotTimeout=5,
+ )
+
+ def get_settings_version(self):
+ return 1
+
+ def on_settings_migrate(self, target, current):
+ if current is None:
+ config = self._settings.global_get(["webcam"])
+ if config:
+ self._logger.info(
+ "Migrating settings from webcam to plugins.classicwebcam..."
+ )
+
+ # flipH
+ self._settings.set_boolean(["flipH"], config.get("flipH", False))
+ self._settings.global_remove(["webcam", "flipH"])
+
+ # flipV
+ self._settings.set_boolean(["flipV"], config.get("flipV", False))
+ self._settings.global_remove(["webcam", "flipV"])
+
+ # rotate90
+ self._settings.set_boolean(["rotate90"], config.get("rotate90", False))
+ self._settings.global_remove(["webcam", "rotate90"])
+
+ # stream
+ self._settings.set(["stream"], config.get("stream", ""))
+ self._settings.global_remove(["webcam", "stream"])
+
+ # streamTimeout
+ self._settings.set_int(["streamTimeout"], config.get("streamTimeout", 5))
+ self._settings.global_remove(["webcam", "streamTimeout"])
+
+ # streamRatio
+ self._settings.set(["streamRatio"], config.get("streamRatio", "16:9"))
+ self._settings.global_remove(["webcam", "streamRatio"])
+
+ # streamWebrtcIceServers
+ self._settings.set(
+ ["streamWebrtcIceServers"],
+ config.get(
+ "streamWebrtcIceServers", ["stun:stun.l.google.com:19302"]
+ ),
+ )
+ self._settings.global_remove(["webcam", "streamWebrtcIceServers"])
+
+ # snapshot
+ self._settings.set(["snapshot"], config.get("snapshot", ""))
+ self._settings.global_remove(["webcam", "snapshot"])
+
+ # cacheBuster
+ self._settings.set_boolean(
+ ["cacheBuster"], config.get("cacheBuster", False)
+ )
+ self._settings.global_remove(["webcam", "cacheBuster"])
+
+ # snapshotTimeout
+ self._settings.set_int(
+ ["snapshotTimeout"], config.get("snapshotTimeout", 5)
+ )
+ self._settings.global_remove(["webcam", "snapshotTimeout"])
+
+ # snapshotSslValidation
+ self._settings.set_boolean(
+ ["snapshotSslValidation"], config.get("snapshotSslValidation", True)
+ )
+ self._settings.global_remove(["webcam", "snapshotSslValidation"])
+
+ # ~~ WizardPlugin API
+
+ def is_wizard_required(self):
+ required = (
+ not self._get_stream_url()
+ or not self._get_snapshot_url()
+ or not self._settings.global_get(["webcam", "ffmpegPath"])
+ )
+ firstrun = self._settings.global_get(["server", "firstRun"])
+ return required and firstrun
+
+ def get_wizard_version(self):
+ return 1
+
+
+__plugin_name__ = gettext("Classic Webcam")
+__plugin_author__ = "Christian Würthner"
+__plugin_description__ = "Provides a simple webcam viewer in OctoPrint's UI, images provided by an MJPEG webcam."
+__plugin_disabling_discouraged__ = gettext(
+ "This plugin provides the standard webcam in OctoPrint. If you do not have any other plugin providing a webcam set up, the webcam section in the control tab will no longer be visible."
+)
+__plugin_license__ = "AGPLv3"
+__plugin_pythoncompat__ = ">=3.7,<4"
+__plugin_implementation__ = ClassicWebcamPlugin()
diff --git a/src/octoprint/plugins/classicwebcam/static/css/classicwebcam.css b/src/octoprint/plugins/classicwebcam/static/css/classicwebcam.css
new file mode 100644
index 000000000..5018f1268
--- /dev/null
+++ b/src/octoprint/plugins/classicwebcam/static/css/classicwebcam.css
@@ -0,0 +1,148 @@
+#webcam_video_container {
+ width: 100%;
+ position: relative;
+ outline: none;
+}
+#webcam_video_container .video-controls {
+ position: absolute;
+ bottom: 0px;
+ right: 8px;
+ z-index: 10;
+ opacity: 0.4;
+}
+#webcam_video_container:hover .video-controls {
+ opacity: 1;
+}
+#webcam_video_container #webcam_hls,
+#webcam_video_container #webcam_rtsp {
+ width: 100%;
+ height: 100%;
+}
+#webcam_video_container .webcam_rotated {
+ position: relative;
+ width: 100%;
+ padding-bottom: 56.25%;
+ display: flex;
+ justify-content: center;
+ align-items: center;
+ margin: auto;
+}
+#webcam_video_container .webcam_rotated .rotation_target {
+ position: absolute;
+ transform: rotate(-90deg);
+ width: 100%;
+}
+#webcam_video_container .webcam_rotated .rotation_target div {
+ width: 100%;
+ height: 100%;
+}
+#webcam_video_container .webcam_unrotated {
+ position: relative;
+ width: 100%;
+}
+#webcam_img_container {
+ width: 100%;
+ position: relative;
+ outline: none;
+ background-color: black;
+}
+#webcam_img_container .keycontrol_overlay {
+ position: absolute;
+ left: 10px;
+ right: 10px;
+ bottom: 10px;
+ background: rgba(0, 0, 0, 0.5);
+ font-size: 85%;
+ color: white;
+ padding: 0;
+}
+#webcam_img_container .keycontrol_overlay kbd {
+ border: 1px solid #eeeeee;
+ border-radius: 3px;
+ margin-left: 2px;
+ margin-right: 2px;
+ font-size: 90%;
+ padding: 2px;
+ min-width: 1em;
+}
+#webcam_img_container .keycontrol_overlay .keycontrol_overlay_heading {
+ position: relative;
+ padding: 10px;
+ font-weight: bold;
+}
+#webcam_img_container .keycontrol_overlay .keycontrol_overlay_column {
+ position: relative;
+ width: 45%;
+ padding: 10px;
+ float: left;
+}
+#webcam_img_container .nowebcam {
+ position: absolute;
+ top: 0;
+ left: 0;
+ right: 0;
+ bottom: 0;
+}
+#webcam_img_container .nowebcam .text {
+ color: white;
+ text-align: center;
+ position: relative;
+ margin: auto;
+ width: 80%;
+ top: 50%;
+ transform: translateY(-50%);
+ display: block;
+}
+#webcam_img_container .nowebcam .text.webcam_loading {
+ animation: pulsate 3s ease-out;
+ animation-iteration-count: infinite;
+}
+#webcam_img_container .webcam_rotated {
+ position: relative;
+ width: 100%;
+ padding-bottom: 100%;
+ pointer-events: none;
+}
+#webcam_img_container .webcam_rotated .webcam_fixed_ratio {
+ position: absolute;
+ transform: rotate(-90deg);
+ top: 0;
+ bottom: 0;
+ pointer-events: none;
+}
+#webcam_img_container .webcam_rotated .webcam_fixed_ratio .webcam_fixed_ratio_inner {
+ width: 100%;
+ height: 100%;
+ pointer-events: none;
+}
+#webcam_img_container .webcam_unrotated .webcam_fixed_ratio {
+ width: 100%;
+ pointer-events: none;
+ padding-bottom: 100%;
+ position: relative;
+}
+#webcam_img_container .webcam_unrotated .webcam_fixed_ratio.ratio43 {
+ padding-bottom: 75%;
+}
+#webcam_img_container .webcam_unrotated .webcam_fixed_ratio.ratio169 {
+ padding-bottom: 56.25%;
+}
+#webcam_img_container .webcam_unrotated .webcam_fixed_ratio.ratio1610 {
+ padding-bottom: 62.5%;
+}
+#webcam_img_container .webcam_unrotated .webcam_fixed_ratio .webcam_fixed_ratio_inner {
+ position: absolute;
+ top: 0;
+ bottom: 0;
+ left: 0;
+ right: 0;
+ pointer-events: none;
+}
+#webcam_img_container img {
+ width: 100%;
+ height: 100%;
+ object-fit: contain;
+}
+#webcamTestContainer {
+ min-height: 384px;
+}
diff --git a/src/octoprint/plugins/classicwebcam/static/js/classicwebcam.js b/src/octoprint/plugins/classicwebcam/static/js/classicwebcam.js
new file mode 100644
index 000000000..5e4d82446
--- /dev/null
+++ b/src/octoprint/plugins/classicwebcam/static/js/classicwebcam.js
@@ -0,0 +1,359 @@
+$(function () {
+ function ClassicWebcamViewModel(parameters) {
+ var self = this;
+
+ self.loginState = parameters[0];
+ self.settings = parameters[1];
+ self.webcamStreamVisible = false;
+
+ self.webcamDisableTimeout = undefined;
+ self.webcamLoaded = ko.observable(false);
+ self.webcamMjpgEnabled = ko.observable(false);
+ self.webcamHlsEnabled = ko.observable(false);
+ self.webcamWebRTCEnabled = ko.observable(false);
+ self.webcamError = ko.observable(false);
+ self.webcamMuted = ko.observable(true);
+ self.webRTCPeerConnection = null;
+ self.webcamElementHls = null;
+ self.webcamElementWebrtc = null;
+
+ self.webcamRatioClass = ko.pureComputed(function () {
+ if (self.settings.streamRatio() == "4:3") {
+ return "ratio43";
+ } else {
+ return "ratio169";
+ }
+ });
+
+ self.onBeforeBinding = function () {
+ // Subscribe to rotation event to ensure we update calculations.
+ // We need to wait for the CSS to be updated by KO, thus we use a timeout to
+ // ensure our calculations run after the CSS was updated
+ self.settings.rotate90.subscribe(function () {
+ window.setTimeout(function () {
+ self._updateVideoTagWebcamLayout();
+ }, 1);
+ });
+
+ self.streamUrlEscaped = ko.pureComputed(function () {
+ return encodeURI(self.settings.streamUrl());
+ });
+
+ self.webcamStreamType = ko.pureComputed(function () {
+ try {
+ return self.determineWebcamStreamType(self.streamUrlEscaped());
+ } catch (e) {
+ console.error(e);
+ return "test";
+ }
+ });
+
+ self.webcamStreamValid = ko.pureComputed(function () {
+ var url = self.streamUrlEscaped();
+ return !url || validateWebcamUrl(url);
+ });
+ };
+
+ self.onWebcamVisbilityChange = function (visible) {
+ self.webcamStreamVisible = visible;
+ if (self.webcamStreamVisible) {
+ self._enableWebcam();
+ } else {
+ self._disableWebcam();
+ }
+ };
+
+ self.onEventSettingsUpdated = function (payload) {
+ // the webcam url might have changed, make sure we replace it now if the
+ // view is visible
+ self._enableWebcamIfVisible();
+ };
+
+ self._getActiveWebcamVideoElement = function () {
+ if (self.webcamWebRTCEnabled()) {
+ return self.webcamElementWebrtc;
+ } else {
+ return self.webcamElementHls;
+ }
+ };
+
+ self.launchWebcamPictureInPicture = function () {
+ self._getActiveWebcamVideoElement().requestPictureInPicture();
+ };
+
+ self.launchWebcamFullscreen = function () {
+ self._getActiveWebcamVideoElement().requestFullscreen();
+ };
+
+ self.toggleWebcamMute = function () {
+ self.webcamMuted(!self.webcamMuted());
+ self.webcamElementWebrtc.muted = self.webcamMuted();
+ self.webcamElementHls.muted = self.webcamMuted();
+ };
+
+ self._disableWebcam = function () {
+ // only disable webcam stream if element is out of view for more than 5s,
+ // otherwise we might cause more load by the constant connection creation
+ // than by the actual webcam stream
+
+ // safari bug doesn't release the mjpeg stream, so we just disable this for
+ // safari.
+ if (OctoPrint.coreui.browser.safari) {
+ return;
+ }
+
+ var timeout = self.settings.streamTimeout() || 5;
+ self.webcamDisableTimeout = setTimeout(function () {
+ log.debug("Unloading webcam stream after", timeout, "seconds");
+ $("#webcam_image").attr("src", "");
+ self.webcamLoaded(false);
+ }, timeout * 1000);
+ };
+
+ self._enableWebcamIfVisible = function () {
+ if (self.webcamStreamVisible) {
+ self._enableWebcam();
+ }
+ };
+
+ self._enableWebcam = function () {
+ if (
+ OctoPrint.coreui.selectedTab != "#control" ||
+ !OctoPrint.coreui.browserTabVisible
+ ) {
+ return;
+ }
+
+ if (self.webcamDisableTimeout != undefined) {
+ clearTimeout(self.webcamDisableTimeout);
+ }
+
+ // IF disabled then we dont need to do anything
+ if (self.settings.webcamEnabled() == false) {
+ console.log("Webcam not enabled");
+ return;
+ }
+
+ // Determine stream type and switch to corresponding webcam.
+ var streamType = self.webcamStreamType();
+ if (streamType == "mjpg") {
+ self._switchToMjpgWebcam();
+ } else if (streamType == "hls") {
+ self._switchToHlsWebcam();
+ } else if (isWebRTCAvailable() && streamType == "webrtc") {
+ self._switchToWebRTCWebcam();
+ } else {
+ throw "Unknown stream type " + streamType;
+ }
+ };
+
+ self.onWebcamLoaded = function () {
+ if (self.webcamLoaded()) return;
+
+ log.debug("Webcam stream loaded");
+ self.webcamLoaded(true);
+ self.webcamError(false);
+ };
+
+ self.onWebcamErrored = function () {
+ log.debug("Webcam stream failed to load/disabled");
+ self.webcamLoaded(false);
+ self.webcamError(true);
+ };
+
+ self.onUserPermissionsChanged =
+ self.onUserLoggedIn =
+ self.onUserLoggedOut =
+ function () {
+ self.syncWebcamElements();
+ };
+
+ self.syncWebcamElements = function () {
+ self.webcamElementHls = document.getElementById("webcam_hls");
+ self.webcamElementWebrtc = document.getElementById("webcam_webrtc");
+ };
+
+ self.onStartup = function () {
+ self.syncWebcamElements();
+ };
+
+ self._switchToMjpgWebcam = function () {
+ var webcamImage = $("#webcam_image");
+ var currentSrc = webcamImage.attr("src");
+
+ // safari bug doesn't release the mjpeg stream, so we just set it up the once
+ if (OctoPrint.coreui.browser.safari && currentSrc != undefined) {
+ return;
+ }
+
+ var newSrc = self.streamUrlEscaped();
+
+ if (currentSrc != newSrc) {
+ if (self.settings.cacheBuster()) {
+ if (newSrc.lastIndexOf("?") > -1) {
+ newSrc += "&";
+ } else {
+ newSrc += "?";
+ }
+ newSrc += new Date().getTime();
+ }
+
+ self.webcamLoaded(false);
+ self.webcamError(false);
+ webcamImage.attr("src", newSrc);
+
+ self.webcamHlsEnabled(false);
+ self.webcamMjpgEnabled(true);
+ self.webcamWebRTCEnabled(false);
+ }
+ };
+
+ self._switchToHlsWebcam = function () {
+ var video = self.webcamElementHls;
+ video.onresize = self._updateVideoTagWebcamLayout;
+
+ // Ensure WebRTC is unloaded
+ if (self.webRTCPeerConnection != null) {
+ self.webRTCPeerConnection.close();
+ self.webRTCPeerConnection = null;
+ }
+
+ // Check for native playback options: https://developer.mozilla.org/en-US/docs/Web/API/HTMLMediaElement/canPlayType
+ if (
+ video != null &&
+ typeof video.canPlayType != undefined &&
+ video.canPlayType("application/vnd.apple.mpegurl") == "probably"
+ ) {
+ video.src = self.streamUrlEscaped();
+ } else if (Hls.isSupported()) {
+ self.hls = new Hls();
+ self.hls.loadSource(self.streamUrlEscaped());
+ self.hls.attachMedia(video);
+ }
+
+ self.webcamMjpgEnabled(false);
+ self.webcamHlsEnabled(true);
+ self.webcamWebRTCEnabled(false);
+ };
+
+ self._switchToWebRTCWebcam = function () {
+ if (!isWebRTCAvailable()) {
+ return;
+ }
+ var video = self.webcamElementWebrtc;
+ video.onresize = self._updateVideoTagWebcamLayout;
+
+ // Ensure HLS is unloaded
+ if (self.hls != null) {
+ self.webcamElementHls.src = null;
+ self.hls.destroy();
+ self.hls = null;
+ }
+
+ // 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.streamUrlEscaped(),
+ self.settings.streamWebrtcIceServers()
+ );
+ }
+
+ self.webcamMjpgEnabled(false);
+ self.webcamHlsEnabled(false);
+ self.webcamWebRTCEnabled(true);
+ };
+
+ self._updateVideoTagWebcamLayout = function () {
+ // Get all elements we need
+ var player = self._getActiveWebcamVideoElement();
+ var rotationContainer = document.querySelector(
+ "#webcam_video_container .webcam_rotated"
+ );
+ var rotationTarget = document.querySelector(
+ "#webcam_video_container .webcam_rotated .rotation_target"
+ );
+ var unrotationContainer = document.querySelector(
+ "#webcam_video_container .webcam_unrotated"
+ );
+ var unrotationTarget = document.querySelector(
+ "#webcam_video_container .webcam_unrotated .rotation_target"
+ );
+
+ // If we found the rotation container, the view is rotated 90 degrees. This
+ // means we need to manually calculate the player dimensions and apply them
+ // to the rotation target where height = width and width = height (to
+ // accommodate the rotation). The target is centered in the container and
+ // rotated around its center, so after we manually resized the container
+ // everything will layout nicely.
+ if (rotationContainer && player.videoWidth && player.videoHeight) {
+ // Calculate the height the video will have in the UI, based on the
+ // video width and the aspect ratio.
+ var aspectRatio = player.videoWidth / player.videoHeight;
+ var height = aspectRatio * rotationContainer.offsetWidth;
+
+ // Enforce the height on the rotation container and the rotation target.
+ // Width of the container will be 100%, height will be calculated
+ //
+ // The size of the rotation target (the element that has the 90 deg
+ // transform) is the inverse size of the container (so height -> width
+ // and width -> height)
+ rotationContainer.style.height = height + "px";
+ rotationTarget.style.height = rotationContainer.offsetWidth + "px";
+ rotationTarget.style.width = rotationContainer.offsetHeight + "px";
+
+ // Remove the padding we used to give the element an initial height.
+ rotationContainer.style.paddingBottom = 0;
+ }
+
+ // We are not rotated, clean up all changes we might have done before
+ if (unrotationContainer) {
+ unrotationContainer.style.height = null;
+ unrotationContainer.style.paddingBottom = 0;
+ unrotationTarget.style.height = null;
+ unrotationTarget.style.width = null;
+ }
+ };
+
+ self.determineWebcamStreamType = function (streamUrl) {
+ if (!streamUrl) {
+ throw "Empty streamUrl. Cannot determine stream type.";
+ }
+
+ var parsed = validateWebcamUrl(streamUrl);
+ if (!parsed) {
+ throw "Invalid streamUrl. Cannot determine stream type.";
+ }
+
+ if (parsed.protocol === "webrtc:" || parsed.protocol === "webrtcs:") {
+ return "webrtc";
+ }
+
+ var lastDotPosition = parsed.pathname.lastIndexOf(".");
+ if (lastDotPosition !== -1) {
+ var extension = parsed.pathname.substring(lastDotPosition + 1);
+ if (extension.toLowerCase() === "m3u8") {
+ return "hls";
+ }
+ }
+
+ // By default, 'mjpg' is the stream type.
+ return "mjpg";
+ };
+ }
+
+ OCTOPRINT_VIEWMODELS.push({
+ construct: ClassicWebcamViewModel,
+ dependencies: ["loginStateViewModel", "classicWebcamSettingsViewModel"],
+ elements: ["#classicwebcam_container"]
+ });
+});
diff --git a/src/octoprint/plugins/classicwebcam/static/js/classicwebcam_settings.js b/src/octoprint/plugins/classicwebcam/static/js/classicwebcam_settings.js
new file mode 100644
index 000000000..f8391d8c3
--- /dev/null
+++ b/src/octoprint/plugins/classicwebcam/static/js/classicwebcam_settings.js
@@ -0,0 +1,236 @@
+$(function () {
+ function ClassicWebcamSettingsViewModel(parameters) {
+ var self = this;
+
+ self.loginState = parameters[0];
+ self.settings = parameters[1];
+ self._subscriptions = [];
+
+ self.webRtcServersToText = function (list) {
+ self.streamWebrtcIceServersText(self.streamWebrtcIceServers().join(", "));
+ };
+
+ self.textToWebRtcServers = function (list) {
+ self.streamWebrtcIceServers(
+ splitTextToArray(self.streamWebrtcIceServersText(), ",", true)
+ );
+ };
+
+ self.onBeforeBinding = function () {
+ self.snapshotUrl = self.settings.settings.plugins.classicwebcam.snapshot;
+ self.flipH = self.settings.settings.plugins.classicwebcam.flipH;
+ self.flipV = self.settings.settings.plugins.classicwebcam.flipV;
+ self.rotate90 = self.settings.settings.plugins.classicwebcam.rotate90;
+ self.streamUrl = self.settings.settings.plugins.classicwebcam.stream;
+ self.webcamEnabled = self.settings.settings.webcam.webcamEnabled;
+ self.streamRatio = self.settings.settings.plugins.classicwebcam.streamRatio;
+ self.streamTimeout =
+ self.settings.settings.plugins.classicwebcam.streamTimeout;
+ self.streamWebrtcIceServers =
+ self.settings.settings.plugins.classicwebcam.streamWebrtcIceServers;
+ self.streamWebrtcIceServersText = ko.observable("");
+ self.cacheBuster = self.settings.settings.plugins.classicwebcam.cacheBuster;
+ self.available_ratios = ["16:9", "4:3"];
+
+ self.webRtcServersToText();
+ self.streamWebrtcIceServers.subscribe(function (value) {
+ self.webRtcServersToText();
+ });
+ };
+
+ self.onSettingsBeforeSave = function () {
+ self.textToWebRtcServers();
+ };
+
+ self.onUserSettingsHidden = function () {
+ self.webRtcServersToText();
+ };
+
+ self.streamUrlEscaped = ko.pureComputed(function () {
+ return encodeURI(self.streamUrl());
+ });
+
+ self.streamType = ko.pureComputed(function () {
+ try {
+ return determineWebcamStreamType(self.streamUrlEscaped());
+ } catch (e) {
+ return "";
+ }
+ });
+
+ self.streamValid = ko.pureComputed(function () {
+ var url = self.streamUrlEscaped();
+ return !url || validateWebcamUrl(url);
+ });
+
+ self.testWebcamStreamUrlBusy = ko.observable(false);
+ self.testWebcamStreamUrl = function () {
+ var url = self.streamUrlEscaped();
+ if (!url) {
+ return;
+ }
+
+ if (self.testWebcamStreamUrlBusy()) {
+ return;
+ }
+
+ var text = gettext(
+ "If you see your webcam stream below, the entered stream URL is ok."
+ );
+
+ var streamType;
+ try {
+ streamType = self.streamType();
+ } catch (e) {
+ streamType = "";
+ }
+
+ var webcam_element;
+ var webrtc_peer_connection;
+ if (streamType === "mjpg") {
+ webcam_element = $('');
+ } else if (streamType === "hls") {
+ webcam_element = $(
+ ''
+ );
+ video_element = webcam_element[0];
+ if (video_element.canPlayType("application/vnd.apple.mpegurl")) {
+ video_element.src = url;
+ } else if (Hls.isSupported()) {
+ var hls = new Hls();
+ hls.loadSource(url);
+ hls.attachMedia(video_element);
+ }
+ } else if (isWebRTCAvailable() && streamType === "webrtc") {
+ webcam_element = $(
+ ''
+ );
+ video_element = webcam_element[0];
+
+ webrtc_peer_connection = startWebRTC(
+ video_element,
+ url,
+ self.streamWebrtcIceServers()
+ );
+ } else {
+ throw "Unknown stream type " + streamType;
+ }
+
+ var message = $("
%(content_type)s. Please " +
+ "double check that the URL is returning static images, not multipart data " +
+ "or videos."
+ );
+ errorText = _.sprintf(errorText, {
+ content_type: _.escape(response.response.content_type)
+ });
+ }
+
+ showMessageDialog({
+ title: errorTitle,
+ message: errorText,
+ onclose: function () {
+ self.testWebcamSnapshotUrlBusy(false);
+ }
+ });
+ return;
+ }
+
+ var content = response.response.content;
+ var contentType = response.response.assumed_content_type;
+
+ var mimeType = "image/jpeg";
+ if (contentType) {
+ mimeType = contentType.split(";")[0];
+ }
+
+ var text = gettext(
+ "If you see your webcam snapshot picture below, the entered snapshot URL is ok."
+ );
+ showMessageDialog({
+ title: gettext("Snapshot test"),
+ message: $(
+ "" + + text + + '
+ If you have a webcam, you may now configure it here. +
{% endtrans %} + ++ The Stream URL is the URL OctoPrint uses to embed the + actual webcam stream (which should be an MJPG stream) into the web + interface. This needs to be reachable from your browser. +
+ It may be +
http://host:port/path),//host:port/path),/absolute/path) orrelative/path)+ The Snapshot URL is the URL OctoPrint uses to fetch single + images from the webcam for creating timelapse recordings. This needs to be + a fully qualified URL reachable from the OctoPrint server. +
{% endtrans %} + + diff --git a/src/octoprint/templates/snippets/settings/webcam/webcamCacheBuster.jinja2 b/src/octoprint/plugins/classicwebcam/templates/snippets/classicwebcamCacheBuster.jinja2 similarity index 83% rename from src/octoprint/templates/snippets/settings/webcam/webcamCacheBuster.jinja2 rename to src/octoprint/plugins/classicwebcam/templates/snippets/classicwebcamCacheBuster.jinja2 index 6ecbd290d..94c3d63dc 100644 --- a/src/octoprint/templates/snippets/settings/webcam/webcamCacheBuster.jinja2 +++ b/src/octoprint/plugins/classicwebcam/templates/snippets/classicwebcamCacheBuster.jinja2 @@ -1,7 +1,7 @@