From 58086a29282e85c71ce16bd3e4713ef59941d02d Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Christian=20W=C3=BCrthner?= Date: Tue, 17 Jan 2023 11:22:56 +0100 Subject: [PATCH 1/8] =?UTF-8?q?=E2=9C=A8=20Move=20webcam=20functionality?= =?UTF-8?q?=20into=20new=20plugin=20type=20(#4628)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit * Create new WebcamPlugin type * Let user switch webcam plugin * Move keyboard controls * Rename webcam plugin * Rename webcam plugin * Update settings pane * Extract JS code from control.js * Temporary fix for KO bindings * Migrate settings to plugin * Fix issue on tab change * Migrate settings UI * Join WebRTC servers to string on migration * Allow list of all webcams to be retrieved * Enricht settings with webcams and ensure backwards compatibility * Fix binfing lost bug * Do not contain webcam settings if permission is missing * Style tabs * Unload webcam based on visibility * Let user pick default webcam * Refactor webcam access in Python * Show snapshot and stream URL in settings dialog * Update timelapse * Small UI improvements * Ensure default webcam is used if nothign is set * Remove dummy webcams * Remove commented sections * Fix CI build * Ensure configuration types are correct * Only show selector if more than one webcam is available * Access default webcam savely in case not set * Use enum values for stream ratio * Address PR comments * Convert data structure to dict * Create function to get snapshot, remove force=True from migration * Fix timelapse not captured * Fix inverted condition check * Update wording in timelapse error message * Apply rotate/flip to timelapse * Add compatibility layer for plugins * Remove exclusion of classicwebcam plugin * Fix unit tests * Fix unit tests #2 * Add onWebcamVisbilityChange callback * Move stream and snapshot wizard to plugin * Replace classic_webcam with classicwebcam * Rename WebcamPlugin to WebcamProviderPlugin * Rename take_snapshot to take_webcam_snapshot * Update copyright * Default to empty dict * Wrap WebcamCompatibility into Optional * Rename CoreWizardWebcamViewModel to ClassicWebcamWizardViewModel * Simplify settings dict creation * Use plugin identifier for logging * Add file header * Simplify toDict() function and renamt to to_dict() * Rename iter to snapshot * Remove redundant boolean checks * Replace with * Add WebcamNotAbleToTakeSnapshotException * Reset wizard version to 1 * Reset wizard version to 1 * Update disabling discouraged messgae * Update default webcam description * Simplify webcam collection * Remove test webcam * 🐛 Fix wrong data location * ♻️ Refactor settings compatibility layer Use a settings overlay centrally derived on server start/platform initialization. Mark overlay as deprecated so that warnings on read and write access will be logged to overlay leaves, and writes will also be denied. Adjust octoprint.webcams methods to allow injecting plugin manager and settings instance to use to support use during initialization. TODO: Reset overlay when default webcam changes? TODO: If we split the compat layer then we should also add TWO overlays, one for snapshot and one for stream config stuff. * 💚 Fix unit tests * ♻️ Move webcam related schema Webcam, WebcamCompatibility and RatioEnum have nothing to do with the config anymore but are rather WebcamProviderPlugin specific, so let's move them into their own octoprint.schema.webcam package. * Remove old wizard logic * Add seprate setting got snapshot webcam * Convert WebRTC servers to list * 🚸 Log warning on deprecated settings on API If anyone is trying to set stuff from the webcam compat layer, we now get a log entry, or multiple if needed. Long term we might want to return an error on the API * ☂ Ensure plugin can actually be found Also use API methods of plugin manager instead of accessing internal control properties directly. Co-authored-by: Gina Häußge --- src/octoprint/__init__.py | 26 + src/octoprint/cli/__init__.py | 2 + src/octoprint/plugin/__init__.py | 8 +- src/octoprint/plugin/types.py | 27 + .../plugins/classicwebcam/__init__.py | 248 ++ .../static/css/classicwebcam.css | 148 + .../classicwebcam/static/js/classicwebcam.js | 359 ++ .../static/js/classicwebcam_settings.js | 236 ++ .../static/js/classicwebcam_wizard.js | 19 + .../static/less/classicwebcam.less | 183 ++ .../templates/classicwebcam_settings.jinja2 | 23 + .../templates/classicwebcam_webcam.jinja2 | 47 + .../templates/classicwebcam_wizard.jinja2 | 31 + .../snippets/classicwebcamCacheBuster.jinja2} | 2 +- .../snippets/classicwebcamOrientation.jinja2 | 17 + .../snippets/classicwebcamSnapshotUrl.jinja2 | 10 + .../snippets/classicwebcamStreamRatio.jinja2} | 2 +- .../classicwebcamStreamTimeout.jinja2} | 2 +- .../snippets/classicwebcamStreamUrl.jinja2 | 13 + ...lassicwebcamStreamWebrtcIceServers.jinja2} | 2 +- .../corewizard/static/js/corewizard.js | 33 - src/octoprint/schema/config/webcam.py | 33 +- src/octoprint/schema/webcam/__init__.py | 72 + src/octoprint/server/__init__.py | 2 + src/octoprint/server/api/settings.py | 129 +- src/octoprint/server/views.py | 10 +- src/octoprint/settings/__init__.py | 40 +- src/octoprint/static/css/octoprint.css | 2928 ++++++++++++++++- .../static/js/app/viewmodels/control.js | 352 +- .../static/js/app/viewmodels/settings.js | 218 +- .../static/js/app/viewmodels/timelapse.js | 51 +- src/octoprint/static/less/octoprint.less | 237 +- .../templates/dialogs/settings/webcam.jinja2 | 15 +- .../settings/webcam/defaultWebcam.jinja2 | 31 + .../settings/webcam/snapshotWebcam.jinja2 | 33 + .../settings/webcam/webcamOrientation.jinja2 | 17 - .../settings/webcam/webcamStreamUrl.jinja2 | 13 - src/octoprint/templates/tabs/control.jinja2 | 78 +- src/octoprint/templates/tabs/timelapse.jinja2 | 18 +- src/octoprint/timelapse.py | 143 +- src/octoprint/webcams.py | 141 + 41 files changed, 5080 insertions(+), 919 deletions(-) create mode 100644 src/octoprint/plugins/classicwebcam/__init__.py create mode 100644 src/octoprint/plugins/classicwebcam/static/css/classicwebcam.css create mode 100644 src/octoprint/plugins/classicwebcam/static/js/classicwebcam.js create mode 100644 src/octoprint/plugins/classicwebcam/static/js/classicwebcam_settings.js create mode 100644 src/octoprint/plugins/classicwebcam/static/js/classicwebcam_wizard.js create mode 100644 src/octoprint/plugins/classicwebcam/static/less/classicwebcam.less create mode 100644 src/octoprint/plugins/classicwebcam/templates/classicwebcam_settings.jinja2 create mode 100644 src/octoprint/plugins/classicwebcam/templates/classicwebcam_webcam.jinja2 create mode 100644 src/octoprint/plugins/classicwebcam/templates/classicwebcam_wizard.jinja2 rename src/octoprint/{templates/snippets/settings/webcam/webcamCacheBuster.jinja2 => plugins/classicwebcam/templates/snippets/classicwebcamCacheBuster.jinja2} (83%) create mode 100644 src/octoprint/plugins/classicwebcam/templates/snippets/classicwebcamOrientation.jinja2 create mode 100644 src/octoprint/plugins/classicwebcam/templates/snippets/classicwebcamSnapshotUrl.jinja2 rename src/octoprint/{templates/snippets/settings/webcam/webcamStreamRatio.jinja2 => plugins/classicwebcam/templates/snippets/classicwebcamStreamRatio.jinja2} (75%) rename src/octoprint/{templates/snippets/settings/webcam/webcamStreamTimeout.jinja2 => plugins/classicwebcam/templates/snippets/classicwebcamStreamTimeout.jinja2} (84%) create mode 100644 src/octoprint/plugins/classicwebcam/templates/snippets/classicwebcamStreamUrl.jinja2 rename src/octoprint/{templates/snippets/settings/webcam/webcamStreamWebrtcIceServers.jinja2 => plugins/classicwebcam/templates/snippets/classicwebcamStreamWebrtcIceServers.jinja2} (85%) create mode 100644 src/octoprint/schema/webcam/__init__.py create mode 100644 src/octoprint/templates/snippets/settings/webcam/defaultWebcam.jinja2 create mode 100644 src/octoprint/templates/snippets/settings/webcam/snapshotWebcam.jinja2 delete mode 100644 src/octoprint/templates/snippets/settings/webcam/webcamOrientation.jinja2 delete mode 100644 src/octoprint/templates/snippets/settings/webcam/webcamStreamUrl.jinja2 create mode 100644 src/octoprint/webcams.py diff --git a/src/octoprint/__init__.py b/src/octoprint/__init__.py index 290ff257a..78e976c15 100644 --- a/src/octoprint/__init__.py +++ b/src/octoprint/__init__.py @@ -507,6 +507,32 @@ def init_settings_plugin_config_migration_and_cleanup(plugin_manager): ] +def init_webcam_compat_overlay(settings, plugin_manager): + import logging + + import octoprint.webcams + + default_webcam = octoprint.webcams.get_default_webcam( + settings=settings, plugin_manager=plugin_manager + ) + if default_webcam is None: + return + + if not default_webcam.config or not default_webcam.config.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.", + ) + + 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 = $( + '