✨ Move webcam functionality into new plugin type (#4628)

* 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 <gina@octoprint.org>
This commit is contained in:
Christian WürthnerandGina Häußge authored and GitHub committed 2023-01-17 11:22:56 +01:00
1 parent 5443b3fe27
commit 58086a2928
41 files changed
+5080 -919

No files matched your search

+26
View File
@@ -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
+2
View File
@@ -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
+5 -3
View File
@@ -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
+27
View File
@@ -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()
@@ -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()
@@ -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;
}
@@ -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"]
});
});
@@ -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 = $('<img src="' + url + '">');
} else if (streamType === "hls") {
webcam_element = $(
'<video id="webcam_hls" muted autoplay style="width: 100%"/>'
);
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 id="webcam_webrtc" muted autoplay playsinline controls style="width: 100%"/>'
);
video_element = webcam_element[0];
webrtc_peer_connection = startWebRTC(
video_element,
url,
self.streamWebrtcIceServers()
);
} else {
throw "Unknown stream type " + streamType;
}
var message = $("<div id='webcamTestContainer'></div>")
.append($("<p></p>"))
.append(text)
.append(webcam_element);
self.testWebcamStreamUrlBusy(true);
showMessageDialog({
title: gettext("Stream test"),
message: message,
onclose: function () {
self.testWebcamStreamUrlBusy(false);
if (webrtc_peer_connection != null) {
webrtc_peer_connection.close();
webrtc_peer_connection = null;
}
}
});
};
self.testWebcamSnapshotUrlBusy = ko.observable(false);
self.testWebcamSnapshotUrl = function (viewModel, event) {
if (!self.snapshotUrl()) {
return;
}
if (self.testWebcamSnapshotUrlBusy()) {
return;
}
var errorText = gettext(
"Could not retrieve snapshot URL, please double check the URL"
);
var errorTitle = gettext("Snapshot test failed");
self.testWebcamSnapshotUrlBusy(true);
OctoPrint.util
.testUrl(self.snapshotUrl(), {
method: "GET",
response: "bytes",
timeout: self.settings.settings.webcam.snapshotTimeout(),
validSsl: self.settings.settings.webcam.snapshotSslValidation(),
content_type_whitelist: ["image/*"],
content_type_guess: true
})
.done(function (response) {
if (!response.result) {
if (
response.status &&
response.response &&
response.response.content_type
) {
// we could contact the server, but something else was wrong, probably the mime type
errorText = gettext(
"Could retrieve the snapshot URL, but it didn't look like an " +
"image. Got this as a content type header: <code>%(content_type)s</code>. 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: $(
"<p>" +
text +
'</p><p><img src="data:' +
mimeType +
";base64," +
content +
'" style="border: 1px solid black" /></p>'
),
onclose: function () {
self.testWebcamSnapshotUrlBusy(false);
}
});
})
.fail(function () {
showMessageDialog({
title: errorTitle,
message: errorText,
onclose: function () {
self.testWebcamSnapshotUrlBusy(false);
}
});
});
};
}
OCTOPRINT_VIEWMODELS.push({
construct: ClassicWebcamSettingsViewModel,
dependencies: ["loginStateViewModel", "settingsViewModel"],
elements: ["#classicwebcam_settings"]
});
});
@@ -0,0 +1,19 @@
$(function () {
function ClassicWebcamWizardViewModel(parameters) {
var self = this;
self.settingsViewModel = parameters[0];
self.onWizardFinish = function () {
if (self.settingsViewModel.streamUrl()) {
return "reload";
}
};
}
OCTOPRINT_VIEWMODELS.push({
construct: ClassicWebcamWizardViewModel,
dependencies: ["classicWebcamSettingsViewModel"],
elements: ["#wizard_classicwebcam"]
});
});
@@ -0,0 +1,183 @@
#webcam_video_container {
width: 100%;
position: relative;
outline: none;
.video-controls {
position: absolute;
bottom: 0px;
right: 8px;
z-index: 10;
opacity: 0.4;
}
&:hover {
.video-controls {
opacity: 1;
}
}
#webcam_hls,
#webcam_rtsp {
width: 100%;
height: 100%;
}
.webcam_rotated {
position: relative;
width: 100%;
padding-bottom: 56.25%;
display: flex;
justify-content: center;
align-items: center;
margin: auto;
.rotation_target {
position: absolute;
transform: rotate(-90deg);
width: 100%;
div {
width: 100%;
height: 100%;
}
}
}
.webcam_unrotated {
position: relative;
width: 100%;
}
}
#webcam_img_container {
width: 100%;
position: relative;
outline: none;
background-color: black;
.keycontrol_overlay {
position: absolute;
left: 10px;
right: 10px;
bottom: 10px;
background: rgba(0, 0, 0, 0.5);
font-size: 85%;
color: white;
padding: 0;
kbd {
border: 1px solid #eeeeee;
border-radius: 3px;
margin-left: 2px;
margin-right: 2px;
font-size: 90%;
padding: 2px;
min-width: 1em;
}
.keycontrol_overlay_heading {
position: relative;
padding: 10px;
font-weight: bold;
}
.keycontrol_overlay_column {
position: relative;
width: 45%;
padding: 10px;
float: left;
}
}
.nowebcam {
position: absolute;
top: 0;
left: 0;
right: 0;
bottom: 0;
.text {
color: white;
text-align: center;
position: relative;
margin: auto;
width: 80%;
top: 50%;
transform: translateY(-50%);
display: block;
&.webcam_loading {
animation: pulsate 3s ease-out;
animation-iteration-count: infinite;
}
}
}
.webcam_rotated {
position: relative;
width: 100%;
padding-bottom: 100%;
pointer-events: none;
.webcam_fixed_ratio {
position: absolute;
transform: rotate(-90deg);
top: 0;
bottom: 0;
pointer-events: none;
.webcam_fixed_ratio_inner {
width: 100%;
height: 100%;
pointer-events: none;
}
}
}
.webcam_unrotated {
.webcam_fixed_ratio {
width: 100%;
pointer-events: none;
padding-bottom: 100%;
&.ratio43 {
padding-bottom: 75%;
}
&.ratio169 {
padding-bottom: 56.25%;
}
&.ratio1610 {
padding-bottom: 62.5%;
}
position: relative;
.webcam_fixed_ratio_inner {
position: absolute;
top: 0;
bottom: 0;
left: 0;
right: 0;
pointer-events: none;
}
}
}
img {
width: 100%;
height: 100%;
object-fit: contain;
}
}
// Predict height of webcam test container for modal positioning
// height is 3/4 the fixed modal width, for 4:3 webcam stream.
// Yes it's hardcoded, but so is the modal width.
#webcamTestContainer {
min-height: 384px;
}
@@ -0,0 +1,23 @@
<div id="classicwebcam_settings">
<h3>{{ _('Stream') }}</h3>
<form class="form-horizontal" onsubmit="return false;">
{% include "snippets/classicwebcamStreamUrl.jinja2" %}
{% include "snippets/classicwebcamStreamRatio.jinja2" %}
{% include "snippets/classicwebcamOrientation.jinja2" %}
<div>
<div><small><a href="#" class="muted" data-bind="toggleContent: { class: 'fa-caret-right fa-caret-down', parent: '.form-horizontal', container: '.hide' }"><i class="fas fa-caret-right"></i> {{ _('Advanced options') }}</a></small></div>
<div class="hide">
{% include "snippets/classicwebcamStreamTimeout.jinja2" %}
{% include "snippets/classicwebcamCacheBuster.jinja2" %}
{% include "snippets/classicwebcamStreamWebrtcIceServers.jinja2" %}
</div>
</div>
</form>
<h3>{{ _('Snapshots & Timelapse') }}</h3>
<form class="form-horizontal" onsubmit="return false;">
{% include "snippets/classicwebcamSnapshotUrl.jinja2" %}
</form>
</div>
@@ -0,0 +1,47 @@
<div id="classicwebcam_container">
<!-- Init style with display none to hide the content while we are binding -->
<div "id="webcam_video_container" tabindex="0" data-bind="visible: webcamWebRTCEnabled() || webcamHlsEnabled(), css: { webcam_rotated: settings.rotate90(), webcam_unrotated: !settings.rotate90() }" style="display: none;">
<div class="video-controls btn-group action-buttons">
<div class="btn btn-mini" data-bind="click: function(data, event) { $root.launchWebcamFullscreen() }"><i class="fas fa-expand"></i></div>
<div class="btn btn-mini" data-bind="visible: document.pictureInPictureEnabled, click: function(data, event) { $root.launchWebcamPictureInPicture() }"><i class="fas fa-images"></i></div>
<div class="btn btn-mini" data-bind="click: function(data, event) { $root.toggleWebcamMute() }">
<!-- ko if: webcamMuted() -->
<i class="fas fa-volume-mute"></i>
<!-- /ko -->
<!-- ko ifnot: webcamMuted() -->
<i class="fas fa-volume-up"></i>
<!-- /ko -->
</div>
</div>
<div data-bind="css: { webcam_rotated: settings.rotate90(), webcam_unrotated: !settings.rotate90() }">
<div class="rotation_target">
<div data-bind="css: { flipH: settings.flipH(), flipV: settings.flipV() }">
<video id="webcam_webrtc" muted autoplay playsinline style="width: 100%" data-bind="visible: webcamWebRTCEnabled()"></video>
<video id="webcam_hls" muted autoplay playsinline style="width: 100%" data-bind="visible: webcamHlsEnabled()"></video>
</div>
</div>
</div>
</div>
<!-- Init style with display none to hide the content while we are binding -->
<div id="webcam_img_container" tabindex="0" data-bind="visible: webcamMjpgEnabled()" style="display: none;">
<div class="nowebcam" data-bind="visible: !webcamLoaded()">
<div class="text webcam_loading" data-bind="visible: !webcamLoaded() && !webcamError()">
<p><strong>{{ _('Webcam stream loading...') }}</strong></p>
</div>
<div class="text webcam_error" data-bind="visible: !webcamLoaded() && webcamError()">
<p><strong>{{ _('Webcam stream not loaded') }}</strong></p>
<p data-bind="visible: !loginState.isAdmin()"><small>{{ _('It might not be configured correctly or require authentication. To have this fixed, get in touch with an administrator of this OctoPrint instance.') }}</small></p>
<p data-bind="visible: loginState.isAdmin"><small>{{ _('It might not be configured correctly or require authentication. You can change the URL of the stream under "Settings" > "Classic Webcam" > "Stream URL". If you don\'t have a webcam you can also just disable webcam support there.') }}</small></p>
<p data-bind="visible: loginState.isUser"><small>{{ _('Currently configured stream URL') }}: <a target="_blank" rel="noreferrer" data-bind="attr: {href: settings.streamUrl}, text: settings.streamUrl"></a></small></p>
</div>
</div>
<div id="webcam_rotator" data-bind="css: { webcam_rotated: settings.rotate90(), webcam_unrotated: !settings.rotate90() }">
<div class="webcam_fixed_ratio" data-bind="css: webcamRatioClass">
<div class="webcam_fixed_ratio_inner">
<img id="webcam_image" data-bind="css: { flipH: settings.flipH(), flipV: settings.flipV() }, event: { load: onWebcamLoaded, error: onWebcamErrored }, visible: !webcamError()">
</div>
</div>
</div>
</div>
</div>
@@ -0,0 +1,31 @@
<h3>{{ _('Webcam &amp; Timelapse Recordings') }}</h3>
{% trans %}<p>
If you have a webcam, you may now configure it here.
</p>{% endtrans %}
<h4>{{ _('Webcam') }}</h4>
{% trans %}<p>
The <strong>Stream URL</strong> 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 <strong>from your browser</strong>.
</p><p>
It may be
<ul>
<li>a fully qualified URL (<code>http://host:port/path</code>),</li>
<li>a URL defaulting to the protocol used for accessing the web
interface (e.g. <code>//host:port/path</code>),</li>
<li>an absolute path on the same host as OctoPrint (e.g. <code>/absolute/path</code>) or</li>
<li>a relative path on the same host as OctoPrint (e.g. <code>relative/path</code>)</li>
</ul>
</p><p>
The <strong>Snapshot URL</strong> 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 <strong>from the OctoPrint server</strong>.
</p>{% endtrans %}
<form id="wizard_classicwebcam" class="form-horizontal" data-bind="with: settingsViewModel" onsubmit="return false;">
{% include "snippets/classicwebcamStreamUrl.jinja2" %}
{% include "snippets/classicwebcamSnapshotUrl.jinja2" %}
</form>
@@ -1,7 +1,7 @@
<div class="control-group" title="{{ _('Enable the cache buster on the webcam URl')|edq }}">
<div class="controls">
<label class="checkbox">
<input type="checkbox" data-bind="checked: webcam_cacheBuster" id="settings-webcamCacheBuster">
<input type="checkbox" data-bind="checked: cacheBuster" id="settings-webcamCacheBuster">
{{ _('Enable Cache buster') }}
<span class="help-block">
<span class="label label-warning">{{ _("Warning") }}</span>
@@ -0,0 +1,17 @@
<div class="control-group">
<div class="controls">
<label class="checkbox">
<input type="checkbox" data-bind="checked: flipH" id="settings-webcamFlipH"> {{ _('Flip webcam horizontally') }}
</label>
</div>
<div class="controls">
<label class="checkbox">
<input type="checkbox" data-bind="checked: flipV" id="settings-webcamFlipV"> {{ _('Flip webcam vertically') }}
</label>
</div>
<div class="controls">
<label class="checkbox">
<input type="checkbox" data-bind="checked: rotate90" id="settings-webcamRotate90"> {{ _('Rotate webcam 90 degrees counter clockwise') }}
</label>
</div>
</div>
@@ -0,0 +1,10 @@
<div class="control-group" title="{{ _('URL to use for retrieving webcam snapshot images for timelapse creation')|edq }}">
<label class="control-label" for="settings-webcamSnapshotUrl">{{ _('Snapshot URL') }}</label>
<div class="controls">
<div class="input-append">
<input type="text" class="input-block-level" data-bind="value: snapshotUrl, valueUpdate: 'afterkeydown'" id="settings-webcamSnapshotUrl">
<button class="btn" type="button" data-bind="click: testWebcamSnapshotUrl, enable: snapshotUrl() && !testWebcamSnapshotUrlBusy(), css: {disabled: !snapshotUrl() || testWebcamSnapshotUrlBusy()}"><i class="fas fa-spinner fa-spin" data-bind="visible: testWebcamSnapshotUrlBusy"></i> {{ _('Test') }}</button>
</div>
<span class="help-inline">{% trans %}Fully qualified URL, needs to be reachable by OctoPrint's server{% endtrans %}</span>
</div>
</div>
@@ -1,7 +1,7 @@
<div class="control-group" title="{{ _('Aspect ratio of the webcam stream, either 16:9 or 4:3')|edq }}">
<label class="control-label" for="settings-webcamStreamRatio">{{ _('Stream aspect ratio') }}</label>
<div class="controls">
<select data-bind="options: webcam_available_ratios, value: webcam_streamRatio" id="settings-webcamStreamRatio"></select>
<select data-bind="options: available_ratios, value: streamRatio" id="settings-webcamStreamRatio"></select>
<span class="help-inline">{% trans %}If the stream has a different aspect ratio than configured here it will be letterboxed.{% endtrans %}</span>
</div>
</div>
@@ -2,7 +2,7 @@
<label class="control-label" for="settings-webcamStreamTimeout">{{ _('Stream timeout') }}</label>
<div class="controls">
<div class="input-append">
<input type="number" min="1" class="input-mini text-right" data-bind="value: webcam_streamTimeout" id="settings-webcamStreamTimeout">
<input type="number" min="1" class="input-mini text-right" data-bind="value: streamTimeout" id="settings-webcamStreamTimeout">
<span class="add-on">sec</span>
</div>
</div>
@@ -0,0 +1,13 @@
<div class="control-group" title="{{ _('URL to embed into the UI for live viewing of the webcam stream')|edq }}" data-bind="css: { error: !streamValid() }">
<label class="control-label" for="settings-webcamStreamUrl">{{ _('Stream URL') }}</label>
<div class="controls">
<div class="input-append">
<input type="text" class="input-block-level" data-bind="value: streamUrl, valueUpdate: 'afterkeydown'" id="settings-webcamStreamUrl">
<button class="btn" type="button" data-bind="click: testWebcamStreamUrl, enable: !testWebcamStreamUrlBusy() && streamValid(), css: {disabled: testWebcamStreamUrlBusy() || !streamValid()}"><i class="fas fa-spinner fa-spin" data-bind="visible: testWebcamStreamUrlBusy"></i> {{ _('Test') }}</button>
</div>
<span class="help-block">
<p>{% trans %}Needs to be reachable from the browser displaying the OctoPrint UI, used to embed the webcam stream into the page.{% endtrans %}</p>
<p data-bind="visible: streamType() === 'webrtc'">{% trans %}<strong>Heads-up!</strong> WebRTC support is still in beta and subject to change, monitor the changelog of future versions closely for heads-ups regarding the WebRTC support in OctoPrint.{% endtrans %}</p>
</span>
</div>
</div>
@@ -1,7 +1,7 @@
<div class="control-group" title="{{ _('ICE server (STUN and/or TURN) to use for WebRTC')|edq }}">
<label class="control-label" for="settings-webcamStreamWebrtcIceServers">{{ _('WebRTC ICE endpoint') }}</label>
<div class="controls">
<input type="text" class="input-block-level" data-bind="value: webcam_streamWebrtcIceServers, valueUpdate: 'afterkeydown'" id="settings-webcamStreamWebrtcIceServers">
<input type="text" class="input-block-level" data-bind="value: streamWebrtcIceServersText, valueUpdate: 'afterkeydown'" id="settings-webcamStreamWebrtcIceServers">
<span class="help-block"><span class="label">{{ _('WebRTC') }}</span> {% trans %}Only used for WebRTC streams. Optionally specify the ICE server(s) (STUN and/or TURN) to use for WebRTC. Multiple servers should be separated by a comma. If unsure, leave at the default of <code>stun:stun.l.google.com:19302</code>.{% endtrans %}</span>
</div>
</div>
@@ -106,34 +106,6 @@ $(function () {
};
}
function CoreWizardWebcamViewModel(parameters) {
var self = this;
self.settingsViewModel = parameters[0];
self.required = false;
self.onWizardDetails = function (response) {
self.required =
response &&
response.corewizard &&
response.corewizard.details &&
response.corewizard.details.webcam &&
response.corewizard.details.webcam.required;
};
self.onWizardFinish = function () {
if (!self.required) return;
if (
self.settingsViewModel.webcam_streamUrl() ||
(self.settingsViewModel.webcam_snapshotUrl() &&
self.settingsViewModel.webcam_ffmpegPath())
) {
return "reload";
}
};
}
function CoreWizardServerCommandsViewModel(parameters) {
var self = this;
@@ -359,11 +331,6 @@ $(function () {
dependencies: ["loginStateViewModel"],
elements: ["#wizard_plugin_corewizard_acl"]
},
{
construct: CoreWizardWebcamViewModel,
dependencies: ["settingsViewModel"],
elements: ["#wizard_plugin_corewizard_webcam"]
},
{
construct: CoreWizardServerCommandsViewModel,
dependencies: ["settingsViewModel"],
+3 -30
View File
@@ -2,17 +2,12 @@ __license__ = "GNU Affero General Public License http://www.gnu.org/licenses/agp
__copyright__ = "Copyright (C) 2022 The OctoPrint Project - Released under terms of the AGPLv3 License"
from enum import Enum
from typing import List, Optional
from typing import Optional
from octoprint.schema import BaseModel
from octoprint.vendor.with_attrs_docs import with_attrs_docs
class RatioEnum(str, Enum):
sixteen_nine = "16:9"
four_three = "4:3"
class TimelapseTypeEnum(str, Enum):
off = "off"
zchange = "zchange"
@@ -54,20 +49,6 @@ class WebcamConfig(BaseModel):
timelapseEnabled: bool = True
"""Use this option to enable timelapse support via snapshot, e.g. via MJPG-Streamer. Timelapse support will be disabled if not set."""
stream: Optional[str] = None
streamRatio: RatioEnum = RatioEnum.sixteen_nine
streamTimeout: int = 5
streamWebrtcIceServers: List[str] = ["stun:stun.l.google.com:19302"]
snapshot: Optional[str] = None
snapshotTimeout: int = 5
snapshotSslValidation: bool = True
ffmpeg: Optional[str] = None
"""Path to ffmpeg binary to use for creating timelapse recordings. Timelapse support will be disabled if not set."""
@@ -83,15 +64,6 @@ class WebcamConfig(BaseModel):
watermark: bool = True
"""Whether to include a "created with OctoPrint" watermark in the generated timelapse recordings."""
flipH: bool = False
"""Whether to flip the webcam horizontally."""
flipV: bool = False
"""Whether to flip the webcam vertically."""
rotate90: bool = False
"""Whether to rotate the webcam 90° counter clockwise."""
ffmpegCommandline: str = '{ffmpeg} -framerate {fps} -i "{input}" -vcodec {videocodec} -threads {threads} -b:v {bitrate} -f {containerformat} -y {filters} "{output}"'
ffmpegThumbnailCommandline: str = (
@@ -104,4 +76,5 @@ class WebcamConfig(BaseModel):
cleanTmpAfterDays: int = 7
"""After how many days unrendered timelapses will be deleted."""
cacheBuster: bool = False
defaultWebcam: str = "classic"
"""The name of the default webcam"""
+72
View File
@@ -0,0 +1,72 @@
__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"
from enum import Enum
from typing import List, Optional
from octoprint.schema import BaseModel
from octoprint.vendor.with_attrs_docs import with_attrs_docs
class RatioEnum(str, Enum):
sixteen_nine = "16:9"
four_three = "4:3"
@with_attrs_docs
class WebcamCompatibility(BaseModel):
streamTimeout: int = 5
"""The timeout of the stream in seconds"""
streamRatio: RatioEnum = RatioEnum.sixteen_nine
"""The stream's native aspect ratio"""
streamWebrtcIceServers: List[str] = ["stun:stun.l.google.com:19302"]
"""The WebRTC STUN and TURN servers"""
cacheBuster: bool = False
"""Whether the the URL should be randomized to bust caches"""
stream: str
"""The URL to get an MJPEG stream from"""
snapshot: str = None
"""The URL to get the snapshot from"""
snapshotTimeout: int = 5
"""The timeout when retrieving snapshots"""
snapshotSslValidation: bool = True
"""Whether to validate SSL certificates when retrieving a snapshot"""
@with_attrs_docs
class Webcam(BaseModel):
name: str
"""Identifier of this webcam"""
displayName: str
"""Displayable name for this webcam"""
canSnapshot: bool = False
"""Whether this webcam can take a snapshot."""
snapshotDisplay: str = None
"""Human readable information about how a snapshot is captured or a HTTP URL from which the snapshot is loaded (optional, only for user reference)"""
flipH: bool = False
"""Whether to flip the webcam horizontally."""
flipV: bool = False
"""Whether to flip the webcam vertically."""
rotate90: bool = False
"""Whether to rotate the webcam 90° counter clockwise."""
extras: dict = {}
"""Unstructured data describing this webcam"""
compat: Optional[WebcamCompatibility] = None
"""A compatibility configuration to allow older clients to make use of this webcam"""
+2
View File
@@ -609,6 +609,7 @@ class Server:
from octoprint import (
init_custom_events,
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
@@ -625,6 +626,7 @@ class Server:
pluginManager.initialize_implementations()
init_settings_plugin_config_migration_and_cleanup(pluginManager)
init_webcam_compat_overlay(self._settings, pluginManager)
pluginManager.log_all_plugins()
+82 -47
View File
@@ -15,11 +15,29 @@ from octoprint.server import pluginManager, printer, userManager
from octoprint.server.api import NO_CONTENT, api
from octoprint.server.util.flask import no_firstrun_access, with_revalidation_checking
from octoprint.settings import settings, valid_boolean_trues
from octoprint.webcams import (
get_default_webcam,
get_snapshot_webcam,
get_webcams_as_dicts,
)
# ~~ settings
FOLDER_TYPES = ("uploads", "timelapse", "watched")
TIMELAPSE_BITRATE_PATTERN = re.compile(r"\d+[KMGTPEZY]?i?B?", flags=re.IGNORECASE)
DEPRECATED_WEBCAM_KEYS = (
"streamUrl",
"streamRatio",
"streamTimeout",
"streamWebrtcIceServers",
"snapshotUrl",
"snapshotTimeout",
"snapshotSslValidation",
"cacheBuster",
"flipH",
"flipV",
"rotate90",
)
def _lastmodified():
@@ -113,27 +131,6 @@ def getSettings():
"closeModalsWithClick": s.getBoolean(["appearance", "closeModalsWithClick"]),
"showInternalFilename": s.getBoolean(["appearance", "showInternalFilename"]),
},
"webcam": {
"webcamEnabled": s.getBoolean(["webcam", "webcamEnabled"]),
"timelapseEnabled": s.getBoolean(["webcam", "timelapseEnabled"]),
"streamUrl": s.get(["webcam", "stream"]),
"streamRatio": s.get(["webcam", "streamRatio"]),
"streamTimeout": s.getInt(["webcam", "streamTimeout"]),
"streamWebrtcIceServers": s.get(["webcam", "streamWebrtcIceServers"]),
"snapshotUrl": s.get(["webcam", "snapshot"]),
"snapshotTimeout": s.getInt(["webcam", "snapshotTimeout"]),
"snapshotSslValidation": s.getBoolean(["webcam", "snapshotSslValidation"]),
"ffmpegPath": s.get(["webcam", "ffmpeg"]),
"ffmpegCommandline": s.get(["webcam", "ffmpegCommandline"]),
"bitrate": s.get(["webcam", "bitrate"]),
"ffmpegThreads": s.get(["webcam", "ffmpegThreads"]),
"ffmpegVideoCodec": s.get(["webcam", "ffmpegVideoCodec"]),
"watermark": s.getBoolean(["webcam", "watermark"]),
"flipH": s.getBoolean(["webcam", "flipH"]),
"flipV": s.getBoolean(["webcam", "flipV"]),
"rotate90": s.getBoolean(["webcam", "rotate90"]),
"cacheBuster": s.getBoolean(["webcam", "cacheBuster"]),
},
"feature": {
"temperatureGraph": s.getBoolean(["feature", "temperatureGraph"]),
"sdSupport": s.getBoolean(["feature", "sdSupport"]),
@@ -343,6 +340,60 @@ def getSettings():
if len(plugin_settings):
data["plugins"] = plugin_settings
if Permissions.WEBCAM.can() is True:
webcamsDict = get_webcams_as_dicts()
data["webcam"] = {
"webcamEnabled": s.getBoolean(["webcam", "webcamEnabled"]),
"timelapseEnabled": s.getBoolean(["webcam", "timelapseEnabled"]),
"ffmpegPath": s.get(["webcam", "ffmpeg"]),
"ffmpegCommandline": s.get(["webcam", "ffmpegCommandline"]),
"bitrate": s.get(["webcam", "bitrate"]),
"ffmpegThreads": s.get(["webcam", "ffmpegThreads"]),
"ffmpegVideoCodec": s.get(["webcam", "ffmpegVideoCodec"]),
"watermark": s.getBoolean(["webcam", "watermark"]),
# webcams & defaults
"webcams": webcamsDict,
"defaultWebcam": None,
"snapshotWebcam": None,
}
for key in DEPRECATED_WEBCAM_KEYS:
data["webcam"][key] = None
defaultWebcam = get_default_webcam()
if defaultWebcam:
data["webcam"].update(
{
"flipH": defaultWebcam.config.flipH,
"flipV": defaultWebcam.config.flipV,
"rotate90": defaultWebcam.config.rotate90,
"defaultWebcam": defaultWebcam.config.name,
}
)
compatWebcam = defaultWebcam.config.compat if defaultWebcam is not None else None
if compatWebcam:
data["webcam"].update(
{
"streamUrl": compatWebcam.stream,
"streamRatio": compatWebcam.streamRatio,
"streamTimeout": compatWebcam.streamTimeout,
"streamWebrtcIceServers": compatWebcam.streamWebrtcIceServers,
"snapshotUrl": compatWebcam.snapshot,
"snapshotTimeout": compatWebcam.snapshotTimeout,
"snapshotSslValidation": compatWebcam.snapshotSslValidation,
"cacheBuster": compatWebcam.cacheBuster,
}
)
snapshotWebcam = get_snapshot_webcam()
if snapshotWebcam:
data["webcam"].update(
{
"snapshotWebcam": snapshotWebcam.config.name,
}
)
return jsonify(data)
@@ -531,30 +582,18 @@ def _saveSettings(data):
)
if "webcam" in data:
for key in DEPRECATED_WEBCAM_KEYS:
if key in data["webcam"]:
logger.warning(
f"Setting webcam.{key} via the API is no longer supported, please use the individual settings of the default webcam instead."
)
if "webcamEnabled" in data["webcam"]:
s.setBoolean(["webcam", "webcamEnabled"], data["webcam"]["webcamEnabled"])
if "timelapseEnabled" in data["webcam"]:
s.setBoolean(
["webcam", "timelapseEnabled"], data["webcam"]["timelapseEnabled"]
)
if "streamUrl" in data["webcam"]:
s.set(["webcam", "stream"], data["webcam"]["streamUrl"])
if "streamRatio" in data["webcam"] and data["webcam"]["streamRatio"] in (
"16:9",
"4:3",
):
s.set(["webcam", "streamRatio"], data["webcam"]["streamRatio"])
if "streamTimeout" in data["webcam"]:
s.setInt(["webcam", "streamTimeout"], data["webcam"]["streamTimeout"])
if "streamWebrtcIceServers" in data["webcam"] and isinstance(
data["webcam"]["streamWebrtcIceServers"], (list, tuple)
):
s.set(
["webcam", "streamWebrtcIceServers"],
data["webcam"]["streamWebrtcIceServers"],
)
if "snapshotUrl" in data["webcam"]:
s.set(["webcam", "snapshot"], data["webcam"]["snapshotUrl"])
if "snapshotTimeout" in data["webcam"]:
s.setInt(["webcam", "snapshotTimeout"], data["webcam"]["snapshotTimeout"])
if "snapshotSslValidation" in data["webcam"]:
@@ -607,14 +646,10 @@ def _saveSettings(data):
s.set(["webcam", "ffmpegVideoCodec"], data["webcam"]["ffmpegVideoCodec"])
if "watermark" in data["webcam"]:
s.setBoolean(["webcam", "watermark"], data["webcam"]["watermark"])
if "flipH" in data["webcam"]:
s.setBoolean(["webcam", "flipH"], data["webcam"]["flipH"])
if "flipV" in data["webcam"]:
s.setBoolean(["webcam", "flipV"], data["webcam"]["flipV"])
if "rotate90" in data["webcam"]:
s.setBoolean(["webcam", "rotate90"], data["webcam"]["rotate90"])
if "cacheBuster" in data["webcam"]:
s.setBoolean(["webcam", "cacheBuster"], data["webcam"]["cacheBuster"])
if "defaultWebcam" in data["webcam"]:
s.set(["webcam", "defaultWebcam"], data["webcam"]["defaultWebcam"])
if "snapshotWebcam" in data["webcam"]:
s.set(["webcam", "snapshotWebcam"], data["webcam"]["snapshotWebcam"])
if "feature" in data:
if "temperatureGraph" in data["feature"]:
+7 -3
View File
@@ -392,9 +392,7 @@ def index():
enable_timelapse = settings().getBoolean(["webcam", "timelapseEnabled"])
enable_loading_animation = settings().getBoolean(["devel", "showLoadingAnimation"])
enable_sd_support = settings().get(["feature", "sdSupport"])
enable_webcam = settings().getBoolean(["webcam", "webcamEnabled"]) and bool(
settings().get(["webcam", "stream"])
)
enable_webcam = settings().getBoolean(["webcam", "webcamEnabled"])
enable_temperature_graph = settings().get(["feature", "temperatureGraph"])
sockjs_connect_timeout = settings().getInt(["devel", "sockJsConnectTimeout"])
@@ -816,6 +814,11 @@ def fetch_template_data(refresh=False):
"template": lambda x: x + "_wizard.jinja2",
"to_entry": lambda data: (data["name"], data),
},
"webcam": {
"div": lambda x: "webcam_plugin_" + x,
"template": lambda x: x + "_webcam.jinja2",
"to_entry": lambda data: (data["name"], data),
},
"about": {
"div": lambda x: "about_plugin_" + x,
"template": lambda x: x + "_about.jinja2",
@@ -852,6 +855,7 @@ def fetch_template_data(refresh=False):
},
"usersettings": {"add": "append", "key": "name"},
"wizard": {"add": "append", "key": "name", "key_extractor": wizard_key_extractor},
"webcam": {"add": "append", "key": "name"},
"about": {"add": "append", "key": "name"},
"generic": {"add": "append", "key": None},
}
+39 -1
View File
@@ -491,6 +491,7 @@ class Settings:
self._get_preprocessors = {"controls": self._process_custom_controls}
self._set_preprocessors = {}
self._deprecated_paths = {}
self._init_basedir(basedir)
@@ -554,6 +555,14 @@ class Settings:
"CSRF Protection is disabled, this is a security risk. Do not run this in production."
)
def _is_deprecated_path(self, path):
if path and isinstance(path[-1], (list, tuple)):
prefix = path[:-1]
return any(
map(lambda x: tuple(prefix + [x]) in self._deprecated_paths, path[-1])
)
return self._deprecated_paths.get(tuple(path), False)
def _get_default_folder(self, type):
folder = default_settings["folder"][type]
if folder is None:
@@ -917,7 +926,7 @@ class Settings:
self._migrate_config(config)
return config
def add_overlay(self, overlay, at_end=False, key=None):
def add_overlay(self, overlay, at_end=False, key=None, deprecated=None):
assert isinstance(overlay, dict)
if key is None:
@@ -928,6 +937,21 @@ class Settings:
hash.update(overlay_yaml.encode("utf-8"))
key = hash.hexdigest()
if deprecated is not None:
def paths(prefix, data):
if isinstance(data, dict):
for k, v in data.items():
yield from paths(prefix + [k], v)
else:
yield prefix
self._logger.debug(
f"Marking all (recursive) paths in this overlay as deprecated: {overlay}"
)
for path in paths([], overlay):
self._deprecated_paths[tuple(path)] = deprecated
overlay[self.OVERLAY_KEY] = key
if at_end:
self._map.insert_map(-1, overlay)
@@ -1536,6 +1560,13 @@ class Settings:
if not path:
raise NoSuchSettingsPath()
is_deprecated = self._is_deprecated_path(path)
if is_deprecated:
self._logger.warn(
f"DeprecationWarning: Detected access to deprecated settings path {path}, returned value is derived from compatibility overlay. {is_deprecated if isinstance(is_deprecated, str) else ''}"
)
config = {}
chain = self._map.with_config_defaults(config=config, defaults=defaults)
if preprocessors is None:
@@ -1812,6 +1843,13 @@ class Settings:
raise NoSuchSettingsPath()
return
is_deprecated = self._is_deprecated_path(path)
if is_deprecated:
self._logger.warning(
f"[Deprecation] Prevented write of `{value}` to deprecated settings path {path}. {is_deprecated if isinstance(is_deprecated, str) else ''}"
)
return
if self._mtime is not None and self.last_modified != self._mtime:
self.load()
File diff suppressed because it is too large. Load diff
+62 -290
View File
@@ -38,17 +38,6 @@ $(function () {
self.controlsFromServer = [];
self.additionalControls = [];
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.keycontrolActive = ko.observable(false);
self.keycontrolHelpActive = ko.observable(false);
self.keycontrolPossible = ko.pureComputed(function () {
@@ -64,22 +53,66 @@ $(function () {
return self.keycontrolActive() && self.keycontrolPossible();
});
self.webcamRatioClass = ko.pureComputed(function () {
if (self.settings.webcam_streamRatio() == "4:3") {
return "ratio43";
} else {
return "ratio169";
}
});
self._visibleWebcam = undefined;
// 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.webcam_rotate90.subscribe(function () {
window.setTimeout(function () {
self._updateVideoTagWebcamLayout();
}, 1);
});
self._dispatchWebcamVisibilityChange = function (target, visible) {
var vm = ko.dataFor(target.children[0]);
if (vm === self) {
console.debug(
`VM for webcam #${target.id} is not bound, skipping visibility update`
);
} else if (vm === undefined) {
console.debug(
`VM for webcam #${target.id} not found, skipping visibility update`
);
} else if (typeof vm.onWebcamVisbilityChange === "function") {
vm.onWebcamVisbilityChange(visible);
} else {
console.debug(
`VM for webcam #${target.id} does not declare 'onWebcamVisbilityChange(visible)', skipping visibility update (vm=${vm.constructor.name})`
);
}
};
self.onAfterBinding = function () {
// We are using the IntersectionObserver API to determine whether a webcam is visible or not.
// A webcam will not intersect with the control tab if the control tab is invisible because another tab
// is selected or if the webcam isn't shown because another webcam is active.
//
// Whenever the webacam changes visibility we will call onWebcamVisbilityChange() which the webcam's
// VM can use to start or stop the stream.
document
.querySelectorAll("#webcam-group .tab-pane")
.forEach(function (target) {
var options = {
root: document.querySelector("#control"),
rootMargin: "0px",
threshold: 1.0
};
var callback = function (entries) {
var visible = entries[0].isIntersecting;
self._dispatchWebcamVisibilityChange(target, visible);
// Keep track which webcam is currently visible (if any)
if (visible) {
self._visibleWebcam = target;
} else if (self._visibleWebcam === target && !visible) {
self._visibleWebcam = undefined;
}
};
var observer = new IntersectionObserver(callback, options);
observer.observe(target);
});
};
self.onBrowserTabVisibilityChange = function (tabVisible) {
// We also observe the the browser tab. If any webcam is currently visible, we will update
// it with the tab status as well.
if (self._visibleWebcam !== undefined) {
self._dispatchWebcamVisibilityChange(self._visibleWebcam, tabVisible);
}
};
self.settings.printerProfiles.currentProfileData.subscribe(function () {
self._updateExtruderCount();
@@ -136,10 +169,7 @@ $(function () {
self.isLoading(data.flags.loading);
};
self.onEventSettingsUpdated = function (payload) {
// the webcam url might have changed, make sure we replace it now if the
// tab is focused
self._enableWebcam();
self.onEventSettingsUpdated = function () {
self.requestData();
};
@@ -342,28 +372,6 @@ $(function () {
}
};
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.sendJogCommand = function (axis, multiplier, distance) {
if (typeof distance === "undefined") distance = self.distance();
if (
@@ -532,89 +540,9 @@ $(function () {
self.onUserLoggedIn =
self.onUserLoggedOut =
function () {
self.syncWebcamElements();
self.requestData();
};
self._disableWebcam = function () {
// only disable webcam stream if tab is out of focus 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.webcam_streamTimeout() || 5;
self.webcamDisableTimeout = setTimeout(function () {
log.debug("Unloading webcam stream");
$("#webcam_image").attr("src", "");
self.webcamLoaded(false);
}, timeout * 1000);
};
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.webcam_webcamEnabled() == false) {
return;
}
// Determine stream type and switch to corresponding webcam.
var streamType = self.settings.webcam_streamType();
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.onTabChange = function (current, previous) {
if (current == "#control") {
self._enableWebcam();
} else if (previous == "#control") {
self._disableWebcam();
}
};
self.onBrowserTabVisibilityChange = function (status) {
if (status) {
self._enableWebcam();
} else {
self._disableWebcam();
}
};
self.onAllBound = function (allViewModels) {
var additionalControls = [];
callViewModels(allViewModels, "getAdditionalControls", function (method) {
@@ -624,7 +552,6 @@ $(function () {
self.additionalControls = additionalControls;
self.rerenderControls();
}
self._enableWebcam();
self.extrusionAmount(
self.settings.printerProfiles
@@ -633,15 +560,6 @@ $(function () {
);
};
self.syncWebcamElements = function () {
self.webcamElementHls = document.getElementById("webcam_hls");
self.webcamElementWebrtc = document.getElementById("webcam_webrtc");
};
self.onStartup = function () {
self.syncWebcamElements();
};
self.onFocus = function (data, event) {
if (!self.settings.feature_keyboardControl()) return;
self.keycontrolActive(true);
@@ -649,13 +567,13 @@ $(function () {
self.onMouseOver = function (data, event) {
if (!self.settings.feature_keyboardControl()) return;
$("#webcam_container").focus();
$("#webcam_plugins_container").focus();
self.keycontrolActive(true);
};
self.onMouseOut = function (data, event) {
if (!self.settings.feature_keyboardControl()) return;
$("#webcam_container").blur();
$("#webcam_plugins_container").blur();
self.keycontrolActive(false);
};
@@ -753,152 +671,6 @@ $(function () {
self.stripDistanceDecimal = function (distance) {
return distance.toString().replace(".", "");
};
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.settings.webcam_streamUrlEscaped();
if (currentSrc != newSrc) {
if (self.settings.webcam_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.settings.webcam_streamUrlEscaped();
} else if (Hls.isSupported()) {
self.hls = new Hls();
self.hls.loadSource(self.settings.webcam_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.settings.webcam_streamUrlEscaped(),
self.settings.webcam_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;
}
};
}
OCTOPRINT_VIEWMODELS.push({
@@ -108,7 +108,6 @@ $(function () {
}
};
self.webcam_available_ratios = ["16:9", "4:3"];
self.webcam_available_videocodecs = ["libx264", "mpeg2video"];
var auto_locale = {
@@ -142,11 +141,6 @@ $(function () {
self.webcam_webcamEnabled = ko.observable(undefined);
self.webcam_timelapseEnabled = ko.observable(undefined);
self.webcam_streamUrl = ko.observable(undefined);
self.webcam_streamRatio = ko.observable(undefined);
self.webcam_streamTimeout = ko.observable(undefined);
self.webcam_streamWebrtcIceServers = ko.observable(undefined);
self.webcam_snapshotUrl = ko.observable(undefined);
self.webcam_snapshotTimeout = ko.observable(undefined);
self.webcam_snapshotSslValidation = ko.observable(undefined);
self.webcam_ffmpegPath = ko.observable(undefined);
@@ -155,10 +149,9 @@ $(function () {
self.webcam_ffmpegThreads = ko.observable(undefined);
self.webcam_ffmpegVideoCodec = ko.observable(undefined);
self.webcam_watermark = ko.observable(undefined);
self.webcam_flipH = ko.observable(undefined);
self.webcam_flipV = ko.observable(undefined);
self.webcam_rotate90 = ko.observable(undefined);
self.webcam_cacheBuster = ko.observable(undefined);
self.webcam_defaultWebcam = ko.observable(undefined);
self.webcam_snapshotWebcam = ko.observable(undefined);
self.webcam_webcams = ko.observableArray([]);
self.feature_temperatureGraph = ko.observable(undefined);
self.feature_sdSupport = ko.observable(undefined);
@@ -304,20 +297,6 @@ $(function () {
self.webcam_ffmpegPathOk(false);
self.webcam_ffmpegPathBroken(false);
};
self.webcam_streamUrlEscaped = ko.pureComputed(function () {
return encodeURI(self.webcam_streamUrl());
});
self.webcam_streamType = ko.pureComputed(function () {
try {
return determineWebcamStreamType(self.webcam_streamUrlEscaped());
} catch (e) {
return "";
}
});
self.webcam_streamValid = ko.pureComputed(function () {
var url = self.webcam_streamUrlEscaped();
return !url || validateWebcamUrl(url);
});
self.server_onlineCheckText = ko.observable();
self.server_onlineCheckOk = ko.observable(false);
@@ -437,170 +416,6 @@ $(function () {
self.terminalFilters.remove(filter);
};
self.testWebcamStreamUrlBusy = ko.observable(false);
self.testWebcamStreamUrl = function () {
var url = self.webcam_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.webcam_streamType();
} catch (e) {
streamType = "";
}
var webcam_element;
var webrtc_peer_connection;
if (streamType === "mjpg") {
webcam_element = $('<img src="' + url + '">');
} else if (streamType === "hls") {
webcam_element = $(
'<video id="webcam_hls" muted autoplay style="width: 100%"/>'
);
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 id="webcam_webrtc" muted autoplay playsinline controls style="width: 100%"/>'
);
video_element = webcam_element[0];
webrtc_peer_connection = startWebRTC(
video_element,
url,
self.webcam_streamWebrtcIceServers()
);
} else {
throw "Unknown stream type " + streamType;
}
var message = $("<div id='webcamTestContainer'></div>")
.append($("<p></p>"))
.append(text)
.append(webcam_element);
self.testWebcamStreamUrlBusy(true);
showMessageDialog({
title: gettext("Stream test"),
message: message,
onclose: function () {
self.testWebcamStreamUrlBusy(false);
if (webrtc_peer_connection != null) {
webrtc_peer_connection.close();
webrtc_peer_connection = null;
}
}
});
};
self.testWebcamSnapshotUrlBusy = ko.observable(false);
self.testWebcamSnapshotUrl = function (viewModel, event) {
if (!self.webcam_snapshotUrl()) {
return;
}
if (self.testWebcamSnapshotUrlBusy()) {
return;
}
var errorText = gettext(
"Could not retrieve snapshot URL, please double check the URL"
);
var errorTitle = gettext("Snapshot test failed");
self.testWebcamSnapshotUrlBusy(true);
OctoPrint.util
.testUrl(self.webcam_snapshotUrl(), {
method: "GET",
response: "bytes",
timeout: self.webcam_snapshotTimeout(),
validSsl: self.webcam_snapshotSslValidation(),
content_type_whitelist: ["image/*"],
content_type_guess: true
})
.done(function (response) {
if (!response.result) {
if (
response.status &&
response.response &&
response.response.content_type
) {
// we could contact the server, but something else was wrong, probably the mime type
errorText = gettext(
"Could retrieve the snapshot URL, but it didn't look like an " +
"image. Got this as a content type header: <code>%(content_type)s</code>. 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: $(
"<p>" +
text +
'</p><p><img src="data:' +
mimeType +
";base64," +
content +
'" style="border: 1px solid black" /></p>'
),
onclose: function () {
self.testWebcamSnapshotUrlBusy(false);
}
});
})
.fail(function () {
showMessageDialog({
title: errorTitle,
message: errorText,
onclose: function () {
self.testWebcamSnapshotUrlBusy(false);
}
});
});
};
self.testWebcamFfmpegPathBusy = ko.observable(false);
self.testWebcamFfmpegPath = function () {
if (!self.webcam_ffmpegPath()) {
@@ -1183,15 +998,6 @@ $(function () {
});
return result;
}
},
webcam: {
streamWebrtcIceServers: function () {
return splitTextToArray(
self.webcam_streamWebrtcIceServers(),
",",
true
);
}
}
};
@@ -1352,11 +1158,6 @@ $(function () {
profiles: function (value) {
self.temperature_profiles($.extend(true, [], value));
}
},
webcam: {
streamWebrtcIceServers: function (value) {
self.webcam_streamWebrtcIceServers(value.join(", "));
}
}
};
@@ -1568,6 +1369,19 @@ $(function () {
if (!self._startupComplete) return;
self.requestData();
};
self.validURL = function (str) {
var pattern = new RegExp(
"^(https?:\\/\\/)?" + // protocol
"((([a-z\\d]([a-z\\d-]*[a-z\\d])*)\\.)+[a-z]{2,}|" + // domain name
"((\\d{1,3}\\.){3}\\d{1,3}))" + // OR ip (v4) address
"(\\:\\d+)?(\\/[-a-z\\d%_.~+]*)*" + // port and path
"(\\?[;&a-z\\d%_.~+=-]*)?" + // query string
"(\\#[-a-z\\d_]*)?$",
"i"
); // fragment locator
return !!pattern.test(str);
};
}
OCTOPRINT_VIEWMODELS.push({
@@ -21,6 +21,26 @@ $(function () {
self.timelapseFps = ko.observable(self.defaultFps);
self.timelapseRetractionZHop = ko.observable(self.defaultRetractionZHop);
self.timelapseMinDelay = ko.observable(self.defaultMinDelay);
self.snapshotWebcam = ko.pureComputed(function () {
var snapshotWebcamName = self.settings.webcam_snapshotWebcam();
return self.settings.webcam_webcams().find(function (w) {
return snapshotWebcamName == w.name;
});
});
self.canSnapshot = ko.pureComputed(function () {
if (!self.snapshotWebcam()) {
return false;
} else {
return self.snapshotWebcam().canSnapshot;
}
});
self.snapshotDisplay = ko.pureComputed(function () {
if (!self.snapshotWebcam()) {
return "";
} else {
return self.snapshotWebcam().snapshotDisplay;
}
});
self.renderProgress = ko.observable();
self.renderTarget = ko.observable();
@@ -684,13 +704,28 @@ $(function () {
gettext(
"Failed repeatedly to capture timelapse frame from webcam - is the snapshot URL configured correctly and the camera on?"
);
html += pnotifyAdditionalInfo(
'Snapshot URL: <pre style="overflow: auto">' +
payload.url +
'</pre>Error: <pre style="overflow: auto">' +
payload.error +
"</pre>"
);
var additional = "";
if (payload.snapshotDisplay) {
additional +=
'Snapshot info: <pre style="overflow: auto">' +
payload.snapshotDisplay +
"</pre>";
}
if (payload.webcamDisplay) {
additional +=
'Webcam: <pre style="overflow: auto">' +
payload.webcamDisplay +
"</pre>";
}
if (payload.error) {
additional +=
'Error: <pre style="overflow: auto">' + payload.error + "</pre>";
}
if (additional) {
html += pnotifyAdditionalInfo(additional);
}
new PNotify({
title: gettext("Could not capture snapshots"),
text: html,
@@ -730,7 +765,7 @@ $(function () {
"<p>" +
_.sprintf(
gettext(
"Rendering of timelapse %(movie_prefix)s is not possible since no frames were captured. Is the snapshot URL configured correctly?"
"Rendering of timelapse %(movie_prefix)s is not possible since no frames were captured. Is the webcam configured correctly?"
),
{movie_prefix: _.escape(payload.movie_prefix)}
) +
+89 -148
View File
@@ -29,7 +29,7 @@ body {
}
}
.brand (@color, @dark, @light) when (@color = @dark) {
.brand (@color, @dark, @light) when (@color =@dark) {
span {
background-image: url(../img/tentacle-20x20.png);
@@ -38,7 +38,8 @@ body {
}
}
}
.brand (@color, @dark, @light) when (@color = @light) {
.brand (@color, @dark, @light) when (@color =@light) {
span {
background-image: url(../img/tentacle-20x20-light.png);
@@ -101,6 +102,7 @@ body {
// invert for dropdown
.navbar-background-color(fade(@bottom, @gradientalpha), fade(@top, @gradientalpha), @image);
}
> li > a:hover {
// darken for hover
@darkenedTop: darken(@top, 5%);
@@ -126,6 +128,7 @@ body {
.navbar-inner-color(@base, 60%, "../img/trans-background.png");
}
}
&.orange {
@base: #f27728;
.navbar-inner-color(@base);
@@ -134,6 +137,7 @@ body {
.navbar-inner-color(@base, 60%, "../img/trans-background.png");
}
}
&.yellow {
@base: #f2de28;
.navbar-inner-color(@base);
@@ -142,6 +146,7 @@ body {
.navbar-inner-color(@base, 60%, "../img/trans-background.png");
}
}
&.green {
@base: #77ff28;
.navbar-inner-color(@base);
@@ -150,6 +155,7 @@ body {
.navbar-inner-color(@base, 60%, "../img/trans-background.png");
}
}
&.blue {
@base: #04c;
.navbar-inner-color(@base);
@@ -158,6 +164,7 @@ body {
.navbar-inner-color(@base, 60%, "../img/trans-background.png");
}
}
&.violet {
@base: #7728ff;
.navbar-inner-color(@base);
@@ -166,6 +173,7 @@ body {
.navbar-inner-color(@base, 60%, "../img/trans-background.png");
}
}
&.black {
@base: #383838;
.navbar-inner-color(@base);
@@ -174,6 +182,7 @@ body {
.navbar-inner-color(@base, 60%, "../img/trans-background.png");
}
}
&.white {
@base: #eeeeee;
.navbar-inner-color(@base);
@@ -337,6 +346,7 @@ table {
text-align: left;
margin: 0 0 0 0;
}
.detail {
text-overflow: ellipsis;
text-align: left;
@@ -414,6 +424,7 @@ table {
position: relative;
.actioncol;
.btn-group {
position: absolute;
bottom: 5px;
@@ -679,71 +690,65 @@ ul.dropdown-menu li a {
}
/** Webcam */
#webcam_video_container {
width: 100%;
#webcam_plugins_container {
@overlay-color: rgba(0, 0, 0, 0.5);
@side-padding: 5px;
@border-radius: 5px;
position: relative;
outline: none;
border-radius: 5px;
margin-top: 6px;
overflow: hidden;
min-height: 300px;
background-color: #000;
.video-controls {
.tab-content {
border: none;
padding: 0px;
}
&:hover .nav {
opacity: 1;
}
.nav {
position: absolute;
bottom: 0px;
right: 8px;
z-index: 10;
opacity: 0.4;
}
padding: @side-padding;
right: @side-padding;
top: @side-padding;
border-radius: @border-radius;
background: @overlay-color;
opacity: 0;
transition: opacity 0.3s, visibility 0.3s;
&:hover {
.video-controls {
opacity: 1;
}
}
.nav-item a {
text-align: end;
padding: @side-padding;
margin-bottom: 1px;
border-radius: @border-radius;
color: white;
#webcam_hls,
#webcam_rtsp {
width: 100%;
height: 100%;
}
.webcam_rotated {
position: relative;
width: 100%;
padding-bottom: 56.25%;
display: flex;
justify-content: center;
align-items: center;
margin: auto;
.rotation_target {
position: absolute;
transform: rotate(-90deg);
width: 100%;
div {
width: 100%;
height: 100%;
&:hover {
background-color: rgba(255, 255, 255, 0.1);
color: white;
}
}
.active {
background-color: rgba(255, 255, 255, 0.2);
border-radius: @border-radius;
color: white;
}
}
.webcam_unrotated {
position: relative;
width: 100%;
}
}
#webcam_container {
width: 100%;
position: relative;
outline: none;
background-color: black;
.keycontrol_overlay {
position: absolute;
left: 10px;
right: 10px;
bottom: 10px;
background: rgba(0, 0, 0, 0.5);
left: @side-padding;
right: @side-padding;
bottom: @side-padding;
border-radius: @border-radius;
overflow: hidden;
background: @overlay-color;
font-size: 85%;
color: white;
padding: 0;
@@ -771,94 +776,6 @@ ul.dropdown-menu li a {
float: left;
}
}
.nowebcam {
position: absolute;
top: 0;
left: 0;
right: 0;
bottom: 0;
.text {
color: white;
text-align: center;
position: relative;
margin: auto;
width: 80%;
top: 50%;
transform: translateY(-50%);
display: block;
&.webcam_loading {
animation: pulsate 3s ease-out;
animation-iteration-count: infinite;
}
}
}
.webcam_rotated {
position: relative;
width: 100%;
padding-bottom: 100%;
pointer-events: none;
.webcam_fixed_ratio {
position: absolute;
transform: rotate(-90deg);
top: 0;
bottom: 0;
pointer-events: none;
.webcam_fixed_ratio_inner {
width: 100%;
height: 100%;
pointer-events: none;
}
}
}
.webcam_unrotated {
.webcam_fixed_ratio {
width: 100%;
pointer-events: none;
padding-bottom: 100%;
&.ratio43 {
padding-bottom: 75%;
}
&.ratio169 {
padding-bottom: 56.25%;
}
&.ratio1610 {
padding-bottom: 62.5%;
}
position: relative;
.webcam_fixed_ratio_inner {
position: absolute;
top: 0;
bottom: 0;
left: 0;
right: 0;
pointer-events: none;
}
}
}
img {
width: 100%;
height: 100%;
object-fit: contain;
}
}
// Predict height of webcam test container for modal positioning
// height is 3/4 the fixed modal width, for 4:3 webcam stream.
// Yes it's hardcoded, but so is the modal width.
#webcamTestContainer {
min-height: 384px;
}
/** State sidebar panel */
@@ -931,10 +848,12 @@ ul.dropdown-menu li a {
}
@highlight-color: yellow;
@keyframes highlightframes {
0% {
background: @highlight-color;
}
100% {
background: transparent;
}
@@ -948,6 +867,7 @@ ul.dropdown-menu li a {
.back {
.back-path {
white-space: nowrap;
span {
word-wrap: break-word;
white-space: pre-line;
@@ -1054,9 +974,11 @@ ul.dropdown-menu li a {
0% {
color: @gray;
}
50% {
color: fade(@gray, 20%);
}
100% {
color: @gray;
}
@@ -1126,6 +1048,7 @@ ul.dropdown-menu li a {
#about_sponsors {
@sponsorCols: 3;
ul {
columns: @sponsorCols;
-webkit-columns: @sponsorCols;
@@ -1135,6 +1058,7 @@ ul.dropdown-menu li a {
#about_authors {
@authorCols: 3;
ul {
columns: @authorCols;
-webkit-columns: @authorCols;
@@ -1155,6 +1079,7 @@ ul.dropdown-menu li a {
display: inline;
margin-left: 1em;
font-size: 85%;
a {
color: #555;
}
@@ -1176,13 +1101,16 @@ ul.dropdown-menu li a {
.ui-pnotify .alert a {
color: #c09853;
}
.ui-pnotify .alert-error a,
.ui-pnotify .alert-danger a {
color: #b94a48;
}
.ui-pnotify .alert-success a {
color: #468847;
}
.ui-pnotify .alert-info a {
color: #3a87ad;
}
@@ -1234,9 +1162,11 @@ textarea.block {
0% {
opacity: 0.5;
}
50% {
opacity: 1;
}
100% {
opacity: 0.5;
}
@@ -1428,7 +1358,7 @@ textarea.block {
background-color: @wellBackground;
border: 1px solid darken(@wellBackground, 7%);
.border-radius(@baseBorderRadius);
.box-shadow(inset 0 1px 1px rgba(0,0,0,0.05));
.box-shadow(inset 0 1px 1px rgba(0, 0, 0, 0.05));
}
&.slider-disabled .slider-track {
@@ -1500,10 +1430,12 @@ _:future,
width: 10px;
height: 10px;
}
::-webkit-scrollbar-track {
border-radius: 10px;
-webkit-border-radius: 10px;
}
::-webkit-scrollbar-thumb {
-webkit-border-radius: 10px;
border-radius: 10px;
@@ -1564,12 +1496,15 @@ _:future,
.add-on {
display: table-cell;
width: 1%; /* remove this if you want default bootstrap button width */
width: 1%;
/* remove this if you want default bootstrap button width */
}
> input {
box-sizing: border-box; /* use bootstrap mixin or include vendor variants */
display: table; /* table-cell is not working well in Chrome for small widths */
box-sizing: border-box;
/* use bootstrap mixin or include vendor variants */
display: table;
/* table-cell is not working well in Chrome for small widths */
min-height: inherit;
width: 100%;
}
@@ -1605,6 +1540,7 @@ input[type="number"].input-nospin::-webkit-inner-spin-button {
-webkit-appearance: none;
margin: 0;
}
input[type="number"].input-nospin {
-moz-appearance: textfield;
}
@@ -1631,11 +1567,13 @@ textarea.monospace {
.progress-text-centered {
position: relative;
.bar {
z-index: 1;
position: absolute;
overflow: hidden;
}
.progress-text-front,
.progress-text-back {
position: absolute;
@@ -1648,6 +1586,7 @@ textarea.monospace {
font-size: 12px;
line-height: 20px;
}
.progress-text-front {
color: #fff;
}
@@ -1797,6 +1736,7 @@ textarea.monospace {
from {
opacity: 0;
}
to {
opacity: 1;
}
@@ -1806,6 +1746,7 @@ textarea.monospace {
from {
opacity: 0;
}
to {
opacity: 0.7;
}
@@ -6,25 +6,14 @@
<form class="form-horizontal" onsubmit="return false;">
{% include "snippets/settings/webcam/webcamEnabled.jinja2" %}
{% include "snippets/settings/webcam/webcamStreamUrl.jinja2" %}
{% include "snippets/settings/webcam/webcamStreamRatio.jinja2" %}
{% include "snippets/settings/webcam/webcamOrientation.jinja2" %}
<div>
<div><small><a href="#" class="muted" data-bind="toggleContent: { class: 'fa-caret-right fa-caret-down', parent: '.form-horizontal', container: '.hide' }"><i class="fas fa-caret-right"></i> {{ _('Advanced options') }}</a></small></div>
<div class="hide">
{% include "snippets/settings/webcam/webcamStreamTimeout.jinja2" %}
{% include "snippets/settings/webcam/webcamCacheBuster.jinja2" %}
{% include "snippets/settings/webcam/webcamStreamWebrtcIceServers.jinja2" %}
</div>
</div>
{% include "snippets/settings/webcam/defaultWebcam.jinja2" %}
</form>
<h3>{{ _('Timelapse Recordings') }}</h3>
<form class="form-horizontal" onsubmit="return false;">
{% include "snippets/settings/webcam/timelapseEnabled.jinja2" %}
{% include "snippets/settings/webcam/webcamSnapshotUrl.jinja2" %}
{% include "snippets/settings/webcam/snapshotWebcam.jinja2" %}
{% include "snippets/settings/webcam/ffmpegPath.jinja2" %}
{% include "snippets/settings/webcam/watermark.jinja2" %}
<div>
@@ -0,0 +1,31 @@
<div class="control-group" title="">
<label class="control-label" for="settings-defaultWebcam">{{ _('Default Webcam') }}</label>
<div class="controls">
<select id="settings-defaultWebcam" data-bind="options: webcam_webcams,
optionsText: function(key) { return key.displayName },
optionsValue: function(key) { return key.name },
value: webcam_defaultWebcam">
</select>
<!-- ko foreach: webcam_webcams -->
<!-- ko if: name == $parent.webcam_defaultWebcam() -->
<span class="help-inline" style="padding-top: 10px; padding-bottom: 10px;">
<span><b>{{ _('MJPEG stream')}}&nbsp;</b></span>
<!-- ko if: compat != null && compat.stream -->
<span data-bind="text: compat.stream"></span>&nbsp;
<a data-bind="attr: { href: compat.stream }" target="_blank"><i class="fa-solid fa-up-right-from-square"></i></a>
<!-- /ko -->
<!-- ko ifnot: compat != null && compat.stream -->
<span>{{ _('Not supported')}}</span>
<!-- /ko -->
</span>
<!-- /ko -->
<!-- /ko -->
<span class="help-inline">{{ _('Selects the default webcam. If this webcam provides a MJPEG video stream, it will be available for old clients that do not make use of the webcam plugin system introduced with OctoPrint 1.9.0') }}</span>
<span class="help-inline" style="padding-top: 10px;">{{ _('You can make changes to this webcam in the plugin\'s settings.') }}</span>
</div>
</div>
@@ -0,0 +1,33 @@
<div class="control-group" title="">
<label class="control-label" for="settings-snapshotWebcam">{{ _('Snapshot Webcam') }}</label>
<div class="controls">
<select id="settings-snapshotWebcam" data-bind="options: webcam_webcams,
optionsText: function(key) { return key.displayName },
optionsValue: function(key) { return key.name },
value: webcam_snapshotWebcam">
</select>
<!-- ko foreach: webcam_webcams -->
<!-- ko if: name == $parent.webcam_snapshotWebcam() -->
<span class="help-inline" style="padding-top: 10px;">
<span><b>{{ _('Snapshot stream')}}&nbsp;</b></span>
<!-- ko if: canSnapshot -->
<!-- ko if: snapshotDisplay -->
<span data-bind="text: snapshotDisplay"></span>&nbsp;
<a data-bind="attr: { href: snapshotDisplay }, visible: $parent.validURL(snapshotDisplay)" target="_blank"><i class="fa-solid fa-up-right-from-square"></i></a>
<!-- /ko -->
<!-- ko ifnot: snapshotDisplay -->
<span>{{ _('Supported')}}</span>
<!-- /ko -->
<!-- /ko -->
<!-- ko ifnot: canSnapshot -->
<span>{{ _('Not supported')}}</span>
<!-- /ko -->
</span>
<!-- /ko -->
<!-- /ko -->
<span class="help-inline" style="padding-top: 10px;">{{ _('You can make changes to this webcam in the plugin\'s settings.') }}</span>
</div>
</div>
@@ -1,17 +0,0 @@
<div class="control-group">
<div class="controls">
<label class="checkbox">
<input type="checkbox" data-bind="checked: webcam_flipH" id="settings-webcamFlipH"> {{ _('Flip webcam horizontally') }}
</label>
</div>
<div class="controls">
<label class="checkbox">
<input type="checkbox" data-bind="checked: webcam_flipV" id="settings-webcamFlipV"> {{ _('Flip webcam vertically') }}
</label>
</div>
<div class="controls">
<label class="checkbox">
<input type="checkbox" data-bind="checked: webcam_rotate90" id="settings-webcamRotate90"> {{ _('Rotate webcam 90 degrees counter clockwise') }}
</label>
</div>
</div>
@@ -1,13 +0,0 @@
<div class="control-group" title="{{ _('URL to embed into the UI for live viewing of the webcam stream')|edq }}" data-bind="css: { error: !webcam_streamValid() }">
<label class="control-label" for="settings-webcamStreamUrl">{{ _('Stream URL') }}</label>
<div class="controls">
<div class="input-append">
<input type="text" class="input-block-level" data-bind="value: webcam_streamUrl, valueUpdate: 'afterkeydown'" id="settings-webcamStreamUrl">
<button class="btn" type="button" data-bind="click: testWebcamStreamUrl, enable: !testWebcamStreamUrlBusy() && webcam_streamValid(), css: {disabled: testWebcamStreamUrlBusy() || !webcam_streamValid()}"><i class="fas fa-spinner fa-spin" data-bind="visible: testWebcamStreamUrlBusy"></i> {{ _('Test') }}</button>
</div>
<span class="help-block">
<p>{% trans %}Needs to be reachable from the browser displaying the OctoPrint UI, used to embed the webcam stream into the page.{% endtrans %}</p>
<p data-bind="visible: webcam_streamType() === 'webrtc'">{% trans %}<strong>Heads-up!</strong> WebRTC support is still in beta and subject to change, monitor the changelog of future versions closely for heads-ups regarding the WebRTC support in OctoPrint.{% endtrans %}</p>
</span>
</div>
</div>
+37 -41
View File
@@ -1,46 +1,41 @@
{% if enableWebcam %}
<!-- ko if: loginState.hasPermissionKo(access.permissions.WEBCAM) -->
<div id="webcam_video_container" tabindex="0" data-bind="visible: webcamWebRTCEnabled() || webcamHlsEnabled(), css: { webcam_rotated: settings.webcam_rotate90(), webcam_unrotated: !settings.webcam_rotate90() }">
<div class="video-controls btn-group action-buttons">
<div class="btn btn-mini" data-bind="click: function(data, event) { $root.launchWebcamFullscreen() }"><i class="fas fa-expand"></i></div>
<div class="btn btn-mini" data-bind="visible: document.pictureInPictureEnabled, click: function(data, event) { $root.launchWebcamPictureInPicture() }"><i class="fas fa-images"></i></div>
<div class="btn btn-mini" data-bind="click: function(data, event) { $root.toggleWebcamMute() }">
<!-- ko if: webcamMuted() -->
<i class="fas fa-volume-mute"></i>
<!-- /ko -->
<!-- ko ifnot: webcamMuted() -->
<i class="fas fa-volume-up"></i>
<!-- /ko -->
</div>
</div>
<div data-bind="css: { webcam_rotated: settings.webcam_rotate90(), webcam_unrotated: !settings.webcam_rotate90() }">
<div class="rotation_target">
<div data-bind="css: { flipH: settings.webcam_flipH(), flipV: settings.webcam_flipV() }">
<video id="webcam_webrtc" muted autoplay playsinline style="width: 100%" data-bind="visible: webcamWebRTCEnabled()"></video>
<video id="webcam_hls" muted autoplay playsinline style="width: 100%" data-bind="visible: webcamHlsEnabled()"></video>
</div>
</div>
</div>
</div>
<div id="webcam_container" tabindex="0" data-bind="event: { keydown: onKeyDown, mouseover: onMouseOver, mouseout: onMouseOut, focus: onFocus }, visible: webcamMjpgEnabled()">
<div class="nowebcam" data-bind="visible: !webcamLoaded()">
<div class="text webcam_loading" data-bind="visible: !webcamLoaded() && !webcamError()">
<p><strong>{{ _('Webcam stream loading...') }}</strong></p>
</div>
<div class="text webcam_error" data-bind="visible: !webcamLoaded() && webcamError()">
<p><strong>{{ _('Webcam stream not loaded') }}</strong></p>
<p data-bind="visible: !loginState.isAdmin()"><small>{{ _('It might not be configured correctly or require authentication. To have this fixed, get in touch with an administrator of this OctoPrint instance.') }}</small></p>
<p data-bind="visible: loginState.isAdmin"><small>{{ _('It might not be configured correctly or require authentication. You can change the URL of the stream under "Settings" > "Webcam & Timelapse" > "Webcam" > "Stream URL". If you don\'t have a webcam you can also just disable webcam support there.') }}</small></p>
<p data-bind="visible: loginState.isUser"><small>{{ _('Currently configured stream URL') }}: <a target="_blank" rel="noreferrer" data-bind="attr: {href: settings.webcam_streamUrl}, text: settings.webcam_streamUrl"></a></small></p>
</div>
</div>
<div id="webcam_rotator" data-bind="css: { webcam_rotated: settings.webcam_rotate90(), webcam_unrotated: !settings.webcam_rotate90() }">
<div class="webcam_fixed_ratio" data-bind="css: webcamRatioClass">
<div class="webcam_fixed_ratio_inner">
<img id="webcam_image" data-bind="css: { flipH: settings.webcam_flipH(), flipV: settings.webcam_flipV() }, event: { load: onWebcamLoaded, error: onWebcamErrored }, visible: !webcamError()">
</div>
<div id="webcam_plugins_container" tabindex="0" data-bind="visible: loginState.hasPermissionKo(access.permissions.WEBCAM), event: { keydown: onKeyDown, mouseover: onMouseOver, mouseout: onMouseOut, focus: onFocus }">
<div class="tabbable row-fluid">
{% set nsContent = namespace(mark_active = True) %}
{% set nsTab = namespace(mark_active = True) %}
<div class="tab-content" id="webcam-group">
{% for key in templates.webcam.order %}
{% set entry, data = templates.webcam.entries[key] %}
{% if data is not none %}
{% if "custom_bindings" not in data or data["custom_bindings"] %}<!-- ko allowBindings: false -->{% endif %}
<div id="{{ data._div }}"
{% if "data_bind" in data %}data-bind="{{ data.data_bind }}"{% endif %}
class="tab-pane {% if nsContent.mark_active %}active{% set nsContent.mark_active = False %}{% endif %} {% if classes_content in data %}{{ data.classes_content|join(' ') }}{% elif classes in data %}{{ data.classes|join(' ') }}{% endif %}"
{% if "styles_content" in data %} style="{{ data.styles_content|join(', ') }}" {% elif styles in data %} style="{{ data.styles|join(', ') }}" {% endif %}
>
{% try "There was an error with the template {filename} at line number {lineno}: {exception}" %}{% include data.template ignore missing %}{% endtry %}
</div>
{% if "custom_bindings" not in data or data["custom_bindings"] %}<!-- /ko -->{% endif %}
{% endif %}
{% endfor %}
</div>
</div>
{% if templates.webcam.order|length > 1 %}
<ul class="nav justify-content-end">
{% for key in templates.webcam.order %}
{% set entry, data = templates.webcam.entries[key] %}
<li id="{{ data._div }}_link"
{% if "data_bind" in data %}data-bind="{{ data.data_bind }}"{% endif %}
class="nav-item {% if nsTab.mark_active %}active{% set nsTab.mark_active = False %}{% endif %}">
<a class="nav-link" href="#{{ data._div }}" data-toggle="tab">{{ entry|e }}</a>
</li>
{% endfor %}
</ul>
{% endif %}
<div class="keycontrol_overlay" data-bind="visible: showKeycontrols">
<div class="keycontrol_overlay_heading">{{ _("Keyboard controls active") }} <a href="#" data-bind="click: toggleKeycontrolHelp"><i class="fas" data-bind="css: { 'fa-chevron-down': !keycontrolHelpActive(), 'fa-chevron-up': keycontrolHelpActive() }"></i></a></div>
<div data-bind="visible: keycontrolHelpActive">
@@ -56,11 +51,12 @@
</div>
</div>
</div>
</div>
<div data-bind="visible: keycontrolPossible() && loginState.hasPermissionKo(access.permissions.WEBCAM)() && loginState.hasPermissionKo(access.permissions.CONTROL)()">
<small class="muted">{{ _("Hint: If you move your mouse over the picture, you enter keyboard control mode.") }}</small>
</div>
<!-- /ko -->
{% endif %}
<div class="jog-panel" style="display: none;" data-bind="visible: loginState.hasPermissionKo(access.permissions.CONTROL)">
+14 -4
View File
@@ -1,5 +1,5 @@
<div data-bind="visible: $root.loginState.hasPermissionKo($root.access.permissions.TIMELAPSE_ADMIN)">
<div style="display: none;" data-bind="visible: settings.webcam_snapshotUrl() && settings.webcam_ffmpegPath()">
<div style="display: none;" data-bind="visible: canSnapshot() && settings.webcam_ffmpegPath()">
<div class="alert" data-bind="visible: isPrinting()">
{{ _('Take note that timelapse configuration is disabled while your printer is printing.') }}
</div>
@@ -90,12 +90,22 @@
</div>
</form>
</div>
<div class="alert" style="display: none" data-bind="visible: !settings.webcam_snapshotUrl() || !settings.webcam_ffmpegPath()">
<div class="alert" style="display: none" data-bind="visible: !canSnapshot() || !settings.webcam_ffmpegPath()">
<p><strong>{{ _('Timelapse not fully configured') }}</strong></p>
<p data-bind="visible: !loginState.isAdmin()">{{ _('The snapshot URL and/or the path to FFMPEG are missing. To have this fixed, get in touch with an administrator of this OctoPrint instance.') }}</p>
<p data-bind="visible: loginState.isAdmin">{{ _('The snapshot URL and/or the path to FFMPEG are missing. You can change both under "Settings" > "Webcam & Timelapse" > "Timelapse". If you don\'t have a webcam or don\'t want to enable timelapse support you can also just disable it there.') }}</p>
<p data-bind="visible: loginState.isAdmin">{{ _('The snapshot URL and/or the path to FFMPEG are missing. You can change both under "Settings" > "Webcam & Timelapse". If you don\'t have a webcam or don\'t want to enable timelapse support you can also just disable it there.') }}</p>
<p data-bind="visible: loginState.isUser"><small>
{{ _('Currently configured snapshot URL') }}: <span data-bind="text: settings.webcam_snapshotUrl"></span><br/>
<!-- ko if: canSnapshot -->
<!-- ko if: snapshotDisplay -->
{{ _('Currently configured snapshot (from default webcam)') }}: <span data-bind="text: snapshotDisplay"></span><br/>
<!-- /ko -->
<!-- ko ifnot: snapshotDisplay -->
{{ _('Snapshots supported by default webcam') }}<br/>
<!-- /ko -->
<!-- /ko -->
<!-- ko ifnot: canSnapshot -->
{{ _('Currently configured default webcam cannot take snapshots') }}<br/>
<!-- /ko -->
{{ _('Currently configured path to FFMPEG') }}: <span data-bind="text: settings.webcam_ffmpegPath"></span>
</small></p>
</div>
+82 -61
View File
@@ -14,7 +14,6 @@ import sys
import threading
import time
import requests
import sarge
import octoprint.plugin
@@ -25,6 +24,7 @@ from octoprint.settings import settings
from octoprint.util import get_fully_qualified_classname as fqcn
from octoprint.util import sv
from octoprint.util.commandline import CommandlineCaller
from octoprint.webcams import WebcamNotAbleToTakeSnapshotException, get_snapshot_webcam
# currently configured timelapse
current = None
@@ -233,26 +233,34 @@ def delete_unrendered_timelapse(name):
def render_unrendered_timelapse(name, gcode=None, postfix=None, fps=None):
capture_dir = settings().getBaseFolder("timelapse_tmp")
output_dir = settings().getBaseFolder("timelapse")
watermark = settings().getBoolean(["webcam", "watermark"])
if fps is None:
fps = settings().getInt(["webcam", "timelapse", "fps"])
threads = settings().get(["webcam", "ffmpegThreads"])
videocodec = settings().get(["webcam", "ffmpegVideoCodec"])
job = TimelapseRenderJob(
capture_dir,
output_dir,
name,
postfix=postfix,
fps=fps,
threads=threads,
videocodec=videocodec,
on_start=_create_render_start_handler(name, gcode=gcode),
on_success=_create_render_success_handler(name, gcode=gcode),
on_fail=_create_render_fail_handler(name, gcode=gcode),
on_always=_create_render_always_handler(name, gcode=gcode),
)
job.process()
webcam = get_snapshot_webcam()
if webcam is None:
logging.getLogger(__name__).error("No webcam configured, can't render timelapse")
else:
job = TimelapseRenderJob(
capture_dir,
output_dir,
name,
postfix=postfix,
fps=fps,
threads=threads,
videocodec=videocodec,
watermark=watermark,
flipH=webcam.config.flipH,
flipV=webcam.config.flipV,
rotate=webcam.config.rotate90,
on_start=_create_render_start_handler(name, gcode=gcode),
on_success=_create_render_success_handler(name, gcode=gcode),
on_fail=_create_render_fail_handler(name, gcode=gcode),
on_always=_create_render_always_handler(name, gcode=gcode),
)
job.process()
def delete_old_unrendered_timelapses():
@@ -403,14 +411,14 @@ def configure_timelapse(config=None, persist=False):
if current is not None:
current.unload()
snapshot_url = settings().get(["webcam", "snapshot"])
snapshot_webcam = get_snapshot_webcam()
can_snapshot = (
snapshot_webcam.config.canSnapshot if snapshot_webcam is not None else False
)
ffmpeg_path = settings().get(["webcam", "ffmpeg"])
timelapse_enabled = settings().getBoolean(["webcam", "timelapseEnabled"])
timelapse_precondition = (
snapshot_url is not None
and snapshot_url.strip() != ""
and ffmpeg_path is not None
and ffmpeg_path.strip() != ""
can_snapshot is True and ffmpeg_path is not None and ffmpeg_path.strip() != ""
)
type = config["type"]
@@ -496,13 +504,14 @@ class Timelapse:
self._post_roll = post_roll
self._on_post_roll_done = None
self._webcam = get_snapshot_webcam()
if self._webcam is None:
raise Exception("Invalid webcam configuration, missing defaultWebcam")
elif self._webcam.config.canSnapshot is False:
raise WebcamNotAbleToTakeSnapshotException(self._webcam.webcam.name)
self._capture_dir = settings().getBaseFolder("timelapse_tmp")
self._movie_dir = settings().getBaseFolder("timelapse")
self._snapshot_url = settings().get(["webcam", "snapshot"])
self._snapshot_timeout = settings().getInt(["webcam", "snapshotTimeout"])
self._snapshot_validate_ssl = settings().getBoolean(
["webcam", "snapshotSslValidation"]
)
self._fps = fps
@@ -724,23 +733,27 @@ class Timelapse:
def _capture_queue_worker(self):
while self._capture_queue_active:
entry = self._capture_queue.get(block=True)
try:
entry = self._capture_queue.get(block=True)
if (
entry["type"] == self.__class__.QUEUE_ENTRY_TYPE_CAPTURE
and "filename" in entry
):
filename = entry["filename"]
onerror = entry.pop("onerror", None)
self._perform_capture(filename, onerror=onerror)
if (
entry["type"] == self.__class__.QUEUE_ENTRY_TYPE_CAPTURE
and "filename" in entry
):
filename = entry["filename"]
onerror = entry.pop("onerror", None)
self._perform_capture(filename, onerror=onerror)
elif (
entry["type"] == self.__class__.QUEUE_ENTRY_TYPE_CALLBACK
and "callback" in entry
):
args = entry.pop("args", [])
kwargs = entry.pop("kwargs", {})
entry["callback"](*args, **kwargs)
elif (
entry["type"] == self.__class__.QUEUE_ENTRY_TYPE_CALLBACK
and "callback" in entry
):
args = entry.pop("args", [])
kwargs = entry.pop("kwargs", {})
entry["callback"](*args, **kwargs)
except Exception:
self._logger.exception(
"Caught unhandled exception in timelapse queue worker"
)
def _perform_capture(self, filename, onerror=None):
# pre-capture hook
@@ -752,25 +765,23 @@ class Timelapse:
eventManager().fire(Events.CAPTURE_START, {"file": filename})
try:
self._logger.debug(f"Going to capture {filename} from {self._snapshot_url}")
r = requests.get(
self._snapshot_url,
stream=True,
timeout=self._snapshot_timeout,
verify=self._snapshot_validate_ssl,
self._logger.debug(
f"Going to capture {filename} from {self._webcam.config.name} provided by {self._webcam.providerIdentifier}"
)
r.raise_for_status()
snapshot = self._webcam.providerPlugin.take_webcam_snapshot(self._webcam)
with open(filename, "wb") as f:
for chunk in r.iter_content(chunk_size=1024):
for chunk in snapshot:
if chunk:
f.write(chunk)
f.flush()
self._logger.debug(f"Image {filename} captured from {self._snapshot_url}")
self._logger.debug(
f"Image {filename} captured from {self._webcam.config.name} provided by {self._webcam.providerIdentifier}"
)
except Exception as e:
self._logger.exception(
f"Could not capture image {filename} from {self._snapshot_url}"
f"Could not capture image {filename} from {self._webcam.config.name} provided by {self._webcam.providerIdentifier}"
)
self._capture_errors += 1
err = e
@@ -794,7 +805,13 @@ class Timelapse:
onerror()
eventManager().fire(
Events.CAPTURE_FAILED,
{"file": filename, "error": str(err), "url": self._snapshot_url},
{
"file": filename,
"error": str(err),
"webcamDisplay": self._webcam.config.displayName,
"snapshotDisplay": self._webcam.config.snapshotDisplay,
"webcamProvider": self._webcam.providerIdentifier,
},
)
return False
@@ -946,6 +963,10 @@ class TimelapseRenderJob:
capture_glob=_capture_glob,
capture_format=_capture_format,
output_format=_output_format,
flipH=False,
flipV=False,
rotate=False,
watermark=False,
fps=25,
threads=1,
videocodec="mpeg2video",
@@ -968,6 +989,10 @@ class TimelapseRenderJob:
self._on_success = on_success
self._on_fail = on_fail
self._on_always = on_always
self._hflip = flipH
self._vflip = flipV
self._rotate = rotate
self._watermark = watermark
self._thread = None
self._logger = logging.getLogger(__name__)
@@ -1042,12 +1067,8 @@ class TimelapseRenderJob:
)
return
hflip = settings().getBoolean(["webcam", "flipH"])
vflip = settings().getBoolean(["webcam", "flipV"])
rotate = settings().getBoolean(["webcam", "rotate90"])
watermark = None
if settings().getBoolean(["webcam", "watermark"]):
if self._watermark:
watermark = os.path.join(
os.path.dirname(__file__), "static", "img", "watermark.png"
)
@@ -1066,9 +1087,9 @@ class TimelapseRenderJob:
input,
temporary,
self._videocodec,
hflip=hflip,
vflip=vflip,
rotate=rotate,
hflip=self._hflip,
vflip=self._vflip,
rotate=self._rotate,
watermark=watermark,
)
self._logger.debug(f"Executing command: {command_str}")
+141
View File
@@ -0,0 +1,141 @@
__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 logging
import octoprint.plugin
from octoprint.plugin import plugin_manager
from octoprint.schema.webcam import Webcam
def get_webcams(plugin_manager=None):
webcams = dict()
def success_callback(name, plugin, result):
nonlocal webcams
logger = logging.getLogger(__name__)
if result is None:
return
if not isinstance(result, (list, tuple)):
logger.error(
f"Received object from `get_webcam_configurations` of plugin {name} that is not a list of Webcam instances",
extra={"plugin": name},
)
return
for webcam in result:
if not isinstance(webcam, Webcam):
logger.warning(
f"Received object in list from `get_webcam_configurations` of plugin {name} that is not an instance of Webcam, skipping",
extra={"plugin": name},
)
continue
if webcam.name in webcams:
logger.warning(
f"Webcam name {webcam.name} provided by plugin {name} is already in use",
extra={"plugin": name},
)
continue
webcams[webcam.name] = ProvidedWebcam(
config=webcam,
providerIdentifier=name,
)
def error_callback(name, _, exc):
logging.getLogger(__name__).info(exc)
octoprint.plugin.call_plugin(
octoprint.plugin.WebcamProviderPlugin,
"get_webcam_configurations",
sorting_context="WebcamProviderPlugin.get_webcam_configurations",
callback=success_callback,
error_callback=error_callback,
manager=plugin_manager,
)
return webcams
def get_default_webcam(settings=None, plugin_manager=None):
def fallbackFilter(webcam: Webcam):
return webcam.config.compat
return __get_webcam_by_setting("defaultWebcam", fallbackFilter)
def get_snapshot_webcam(settings=None, plugin_manager=None):
def fallbackFilter(webcam: Webcam):
return webcam.config.canSnapshot
return __get_webcam_by_setting("snapshotWebcam", fallbackFilter)
def __get_webcam_by_setting(setting, fallbackFilter, settings=None, plugin_manager=None):
webcams = get_webcams(plugin_manager=plugin_manager)
if not webcams:
return None
if settings is None:
from octoprint.settings import settings as s
settings = s()
name = settings.get(["webcam", setting])
webcam = webcams.get(name)
if webcam:
return webcam
return next(filter(fallbackFilter, iter(webcams.values())), None)
def get_webcams_as_dicts(plugin_manager=None):
def to_dict(webcam):
webcam_dict = webcam.config.dict()
webcam_dict["provider"] = webcam.providerIdentifier
return webcam_dict
return list(map(to_dict, get_webcams(plugin_manager=plugin_manager).values()))
class WebcamNotAbleToTakeSnapshotException(Exception):
"""Raised a webcam that is not able to take a snapshot is used to take a snapshot"""
def __init__(self, webcam_name):
self.webcam_name = webcam_name
self.message = f"Webcam {webcam_name} can't take snapshots"
super().__init__(self.message)
class ProvidedWebcam:
config: Webcam
"""the ``WebcamConfiguration`` configuration"""
providerIdentifier: str
"""identifier of the plugin providing this Webcam"""
providerPlugin: str
"""plugin instance of the plugin providing this Webcam"""
def __init__(self, config, providerIdentifier):
self.config = config
self.providerIdentifier = providerIdentifier
providerPluginInfo = plugin_manager().get_plugin_info(providerIdentifier)
if providerPluginInfo is None:
raise Exception(f"Can't find plugin {providerIdentifier}")
if not providerPluginInfo.implementation:
raise Exception(
f"Plugin {providerIdentifier} does not have an implementation"
)
self.providerPlugin = providerPluginInfo.implementation
if self.config is None:
raise Exception("Can't create ProvidedWebcam with None config")
if self.providerIdentifier is None:
raise Exception("Can't create ProvidedWebcam with None providerIdentifier")