@trap_stevo/legendarybuilderproreact-ui
Version:
The legendary UI & utility API that makes your application a legendary application. ~ Created by Steven Compton
1,133 lines • 49.6 kB
JavaScript
import _extends from "@babel/runtime/helpers/extends";
import _defineProperty from "@babel/runtime/helpers/defineProperty";
import _slicedToArray from "@babel/runtime/helpers/slicedToArray";
import _asyncToGenerator from "@babel/runtime/helpers/asyncToGenerator";
function ownKeys(e, r) { var t = Object.keys(e); if (Object.getOwnPropertySymbols) { var o = Object.getOwnPropertySymbols(e); r && (o = o.filter(function (r) { return Object.getOwnPropertyDescriptor(e, r).enumerable; })), t.push.apply(t, o); } return t; }
function _objectSpread(e) { for (var r = 1; r < arguments.length; r++) { var t = null != arguments[r] ? arguments[r] : {}; r % 2 ? ownKeys(Object(t), !0).forEach(function (r) { _defineProperty(e, r, t[r]); }) : Object.getOwnPropertyDescriptors ? Object.defineProperties(e, Object.getOwnPropertyDescriptors(t)) : ownKeys(Object(t)).forEach(function (r) { Object.defineProperty(e, r, Object.getOwnPropertyDescriptor(t, r)); }); } return e; }
import _regeneratorRuntime from "@babel/runtime/regenerator";
import React, { useState, useEffect, useRef, useCallback } from "react";
import { HUDUniversalHUDUtilityManager, ConvertURLToIP, Countdown, Delay } from "../HUDManagers/HUDUniversalHUDUtilityManager.js";
import HUDOperationsUtilityManager from "../HUDManagers/HUDOperationsUtilityManager.js";
import { useIdleDetection, useTimeout } from "../HUDManagers/HUDUniversalHUDEventEffectsManager.js";
import PropTypes from "prop-types";
var styles = {
container: {
display: "flex",
flexDirection: "column",
alignItems: "center",
justifyContent: "center",
fontFamily: "'Orbitron', sans-serif",
backgroundColor: "#1a1a1a",
color: "#00ffcc",
height: "100vh",
width: "100vw"
},
actionContainer: {
display: "flex",
flexDirection: "column",
justifyContent: "center",
alignItems: "center",
gap: "10px"
},
videoContainer: {
position: "relative",
width: "100%"
},
video: {
borderRadius: "10px",
boxShadow: "0 0 20px rgba(0, 255, 204, 0.569)",
width: "100%"
},
overlay: {
position: "absolute",
display: "flex",
alignItems: "center",
justifyContent: "center",
backgroundColor: "rgba(0, 0, 0, 0.569)",
borderRadius: "10px",
height: "100%",
width: "100%",
zIndex: 1,
left: 0,
top: 0
},
message: {
fontSize: "1.69rem",
color: "#00ffcc",
textShadow: "0 0 10px rgba(0, 255, 204, 0.7)"
},
loadingSpinner: {
border: "6px solid rgba(0, 255, 204, 0.2)",
borderTop: "6px solid #00ffcc",
borderRadius: "50%",
animation: "spin 1s linear infinite",
height: "69px",
width: "69px",
marginBottom: "15px",
marginTop: "20px"
}
};
var keyframes = "\n @keyframes spin {\n 0% { transform : rotate(0deg); }\n 100% { transform : rotate(360deg); }\n }\n";
function log(type) {
var enableLogging = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : true;
var onLog = arguments.length > 2 ? arguments[2] : undefined;
var now = new Date();
var timestamp = now.toLocaleString();
for (var _len = arguments.length, message = new Array(_len > 3 ? _len - 3 : 0), _key = 3; _key < _len; _key++) {
message[_key - 3] = arguments[_key];
}
if (onLog) {
onLog.apply(void 0, ["[".concat(timestamp, "] ").concat(type.toUpperCase() !== "LOG" ? "[".concat(type.toUpperCase(), "]") : "", " :: ")].concat(message));
}
if (!enableLogging) {
return;
}
var logMethod = {
log: console.log,
info: console.info,
warn: console.warn,
error: console.error,
debug: console.debug
}[type] || console.log;
logMethod.apply(void 0, ["[".concat(timestamp, "] ").concat(type.toUpperCase() !== "LOG" ? "[".concat(type.toUpperCase(), "]") : "", " :: ")].concat(message));
}
;
function startStream(_x) {
return _startStream.apply(this, arguments);
}
function _startStream() {
_startStream = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime.mark(function _callee13(signalURL) {
var streamsURL,
streamId,
channelId,
videoRef,
peerConnectionRef,
startCountdown,
stopCountdown,
setConnected,
connecting,
webRTSPStreaming,
enableLogging,
onWebRTSPLog,
onWebRTSPConnect,
streamSignalURL,
streamSignalSRC,
config,
peerConnection,
remoteDesc,
_args13 = arguments;
return _regeneratorRuntime.wrap(function _callee13$(_context13) {
while (1) switch (_context13.prev = _context13.next) {
case 0:
streamsURL = _args13.length > 1 && _args13[1] !== undefined ? _args13[1] : null;
streamId = _args13.length > 2 ? _args13[2] : undefined;
channelId = _args13.length > 3 ? _args13[3] : undefined;
videoRef = _args13.length > 4 ? _args13[4] : undefined;
peerConnectionRef = _args13.length > 5 ? _args13[5] : undefined;
startCountdown = _args13.length > 6 ? _args13[6] : undefined;
stopCountdown = _args13.length > 7 ? _args13[7] : undefined;
setConnected = _args13.length > 8 ? _args13[8] : undefined;
connecting = _args13.length > 9 ? _args13[9] : undefined;
webRTSPStreaming = _args13.length > 10 ? _args13[10] : undefined;
enableLogging = _args13.length > 11 ? _args13[11] : undefined;
onWebRTSPLog = _args13.length > 12 ? _args13[12] : undefined;
onWebRTSPConnect = _args13.length > 13 ? _args13[13] : undefined;
_context13.prev = 13;
streamSignalURL = streamsURL ? streamsURL : "http://".concat(ConvertURLToIP(signalURL), ":8083");
streamSignalSRC = "".concat(streamSignalURL, "/stream/").concat(streamId, "/channel/").concat(channelId, "/webrtc");
connecting.current = true;
log("log", enableLogging, onWebRTSPLog, "WEBRTSP Connection ~ Connecting to source ~ ".concat(streamSignalURL, "..."));
config = {
iceServers: [{
urls: "stun:stun.l.google.com:19302"
}]
};
peerConnection = new RTCPeerConnection(config);
_context13.next = 22;
return prepareNewTrack(streamSignalSRC, peerConnection, videoRef, webRTSPStreaming, stopCountdown);
case 22:
remoteDesc = _context13.sent;
log("log", enableLogging, onWebRTSPLog, "WEBRTSP Connection ~ Got stream connection signal!");
peerConnection.oniceconnectionstatechange = function () {
log("log", enableLogging, onWebRTSPLog, "WEBRTSP Connection ~ Connection state ~ ", peerConnection.iceConnectionState);
if (peerConnection.iceConnectionState === "connected") {
log("log", enableLogging, onWebRTSPLog, "WEBRTSP Connection ~ Connected to source ~ ".concat(streamSignalURL, "!"));
connecting.current = false;
setConnected(true);
webRTSPStreaming();
if (onWebRTSPConnect) {
onWebRTSPConnect();
}
return;
}
if (peerConnection.iceConnectionState === "checking" || peerConnection.iceConnectionState === "connecting") {
connecting.current = true;
webRTSPStreaming();
stopCountdown();
return;
}
if (peerConnection.iceConnectionState === "disconnected") {
connecting.current = true;
setConnected(false);
startCountdown();
}
};
_context13.next = 27;
return peerConnection.setRemoteDescription(remoteDesc);
case 27:
peerConnectionRef.current = peerConnection;
_context13.next = 35;
break;
case 30:
_context13.prev = 30;
_context13.t0 = _context13["catch"](13);
log("error", enableLogging, onWebRTSPLog, "WEBRTSP Connection ~ Did not start stream ~ ", _context13.t0);
connecting.current = true;
setConnected(false);
case 35:
case "end":
return _context13.stop();
}
}, _callee13, null, [[13, 30]]);
}));
return _startStream.apply(this, arguments);
}
;
var prepareNewTrack = /*#__PURE__*/function () {
var _ref = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime.mark(function _callee(streamSignalSRC, peerConnection, videoRef, webRTSPStreaming, stopCountdown) {
var offer, sdpOfferBase64, response, sdpAnswerBase64, sdpAnswer, remoteDesc;
return _regeneratorRuntime.wrap(function _callee$(_context) {
while (1) switch (_context.prev = _context.next) {
case 0:
_context.next = 2;
return peerConnection.createOffer({
offerToReceiveVideo: true
});
case 2:
offer = _context.sent;
_context.next = 5;
return peerConnection.setLocalDescription(offer);
case 5:
sdpOfferBase64 = btoa(offer.sdp);
_context.next = 8;
return fetch(streamSignalSRC, {
method: "POST",
headers: {
"Content-Type": "application/x-www-form-urlencoded"
},
body: new URLSearchParams({
data: sdpOfferBase64
})
});
case 8:
response = _context.sent;
if (response.ok) {
_context.next = 11;
break;
}
throw new Error("Did not get SDP answer ~ ".concat(response.statusText));
case 11:
_context.next = 13;
return response.text();
case 13:
sdpAnswerBase64 = _context.sent;
sdpAnswer = atob(sdpAnswerBase64);
remoteDesc = new RTCSessionDescription({
type: "answer",
sdp: sdpAnswer
});
peerConnection.ontrack = function (event) {
var track = event.track;
webRTSPStreaming();
if (videoRef.current) {
stopCountdown();
var remoteStream = new MediaStream();
remoteStream.addTrack(track);
videoRef.current.srcObject = remoteStream;
}
};
return _context.abrupt("return", remoteDesc);
case 18:
case "end":
return _context.stop();
}
}, _callee);
}));
return function prepareNewTrack(_x2, _x3, _x4, _x5, _x6) {
return _ref.apply(this, arguments);
};
}();
var closePeerConnection = function closePeerConnection(peerConnection) {
if (peerConnection) {
peerConnection.close();
peerConnection = null;
}
};
function rtspToWebStreamDetails(data) {
var result = {};
for (var streamID in data.payload) {
var streamData = data.payload[streamID];
for (var channel in streamData.channels) {
var channelData = streamData.channels[channel];
result[channelData.url] = {
streamID: streamID,
channel: channel
};
}
}
return result;
}
;
function getRTSPToWebStreamDetails(_x7) {
return _getRTSPToWebStreamDetails.apply(this, arguments);
}
function _getRTSPToWebStreamDetails() {
_getRTSPToWebStreamDetails = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime.mark(function _callee14(signalURL) {
var streamsURL,
signalName,
signalID,
enableLogging,
onWebRTSPLog,
url,
headers,
credentials,
response,
data,
_args14 = arguments;
return _regeneratorRuntime.wrap(function _callee14$(_context14) {
while (1) switch (_context14.prev = _context14.next) {
case 0:
streamsURL = _args14.length > 1 && _args14[1] !== undefined ? _args14[1] : null;
signalName = _args14.length > 2 && _args14[2] !== undefined ? _args14[2] : "demo";
signalID = _args14.length > 3 && _args14[3] !== undefined ? _args14[3] : "demo";
enableLogging = _args14.length > 4 ? _args14[4] : undefined;
onWebRTSPLog = _args14.length > 5 ? _args14[5] : undefined;
url = streamsURL ? "".concat(streamsURL, "/streams") : "http://".concat(ConvertURLToIP(signalURL), ":8083/streams");
_context14.prev = 6;
headers = new Headers();
credentials = btoa("".concat(signalName, ":").concat(signalID));
headers.set("Authorization", "Basic ".concat(credentials));
_context14.next = 12;
return fetch(url, {
headers: headers
});
case 12:
response = _context14.sent;
if (response.ok) {
_context14.next = 15;
break;
}
throw new Error("".concat(response.statusText));
case 15:
_context14.next = 17;
return response.json();
case 17:
data = _context14.sent;
return _context14.abrupt("return", rtspToWebStreamDetails(data));
case 21:
_context14.prev = 21;
_context14.t0 = _context14["catch"](6);
log("error", enableLogging, onWebRTSPLog, "WEBRTSP Connection ~ Did not get streams ~ ".concat(_context14.t0));
return _context14.abrupt("return", null);
case 25:
case "end":
return _context14.stop();
}
}, _callee14, null, [[6, 21]]);
}));
return _getRTSPToWebStreamDetails.apply(this, arguments);
}
;
function HUDRTSCViewer(_ref2) {
var _ref2$actionContainer = _ref2.actionContainerConfigurationSettings,
actionContainerConfigurationSettings = _ref2$actionContainer === void 0 ? {} : _ref2$actionContainer,
_ref2$videoContainerC = _ref2.videoContainerConfigurationSettings,
videoContainerConfigurationSettings = _ref2$videoContainerC === void 0 ? {} : _ref2$videoContainerC,
_ref2$loadingSpinnerC = _ref2.loadingSpinnerConfigurationSettings,
loadingSpinnerConfigurationSettings = _ref2$loadingSpinnerC === void 0 ? {} : _ref2$loadingSpinnerC,
_ref2$containerConfig = _ref2.containerConfigurationSettings,
containerConfigurationSettings = _ref2$containerConfig === void 0 ? {} : _ref2$containerConfig,
_ref2$messageConfigur = _ref2.messageConfigurationSettings,
messageConfigurationSettings = _ref2$messageConfigur === void 0 ? {} : _ref2$messageConfigur,
_ref2$overlayConfigur = _ref2.overlayConfigurationSettings,
overlayConfigurationSettings = _ref2$overlayConfigur === void 0 ? {} : _ref2$overlayConfigur,
_ref2$videoConfigurat = _ref2.videoConfigurationSettings,
videoConfigurationSettings = _ref2$videoConfigurat === void 0 ? {} : _ref2$videoConfigurat,
_ref2$webRTSPStreamCo = _ref2.webRTSPStreamConfigurations,
webRTSPStreamConfigurations = _ref2$webRTSPStreamCo === void 0 ? {} : _ref2$webRTSPStreamCo,
_ref2$containerConfig2 = _ref2.containerConfigurations,
containerConfigurations = _ref2$containerConfig2 === void 0 ? {} : _ref2$containerConfig2,
_ref2$clientStreamSet = _ref2.clientStreamSettings,
clientStreamSettings = _ref2$clientStreamSet === void 0 ? {
hardwareAccelerationActivated: true,
enableMaxPerformance: true,
leakyDownstream: false,
maxSizeBuffers: 2,
maxSizeBytes: 10485760,
protocols: "tcp"
} : _ref2$clientStreamSet,
_ref2$clientDetails = _ref2.clientDetails,
clientDetails = _ref2$clientDetails === void 0 ? {} : _ref2$clientDetails,
_ref2$sessionID = _ref2.sessionID,
sessionID = _ref2$sessionID === void 0 ? HUDUniversalHUDUtilityManager.GenerateUUID() : _ref2$sessionID,
_ref2$signalName = _ref2.signalName,
signalName = _ref2$signalName === void 0 ? "demo" : _ref2$signalName,
_ref2$signalID = _ref2.signalID,
signalID = _ref2$signalID === void 0 ? "demo" : _ref2$signalID,
_ref2$signalURL = _ref2.signalURL,
signalURL = _ref2$signalURL === void 0 ? "http://localhost:5069" : _ref2$signalURL,
_ref2$streamsURL = _ref2.streamsURL,
streamsURL = _ref2$streamsURL === void 0 ? null : _ref2$streamsURL,
_ref2$rtspURL = _ref2.rtspURL,
rtspURL = _ref2$rtspURL === void 0 ? "rtsp://localhost:8554" : _ref2$rtspURL,
_ref2$autoDisconnects = _ref2.autoDisconnectsWhenHidden,
autoDisconnectsWhenHidden = _ref2$autoDisconnects === void 0 ? false : _ref2$autoDisconnects,
_ref2$autoDisconnectT = _ref2.autoDisconnectThreshold,
autoDisconnectThreshold = _ref2$autoDisconnectT === void 0 ? 0.169 : _ref2$autoDisconnectT,
_ref2$idleReconnectio = _ref2.idleReconnectionInterval,
idleReconnectionInterval = _ref2$idleReconnectio === void 0 ? "2s" : _ref2$idleReconnectio,
_ref2$reconnectionInt = _ref2.reconnectionInterval,
reconnectionInterval = _ref2$reconnectionInt === void 0 ? 3000 : _ref2$reconnectionInt,
_ref2$restartStreamOn = _ref2.restartStreamOnIdle,
restartStreamOnIdle = _ref2$restartStreamOn === void 0 ? true : _ref2$restartStreamOn,
_ref2$preventSignalCo = _ref2.preventSignalConnections,
preventSignalConnections = _ref2$preventSignalCo === void 0 ? false : _ref2$preventSignalCo,
_ref2$triggerConnecti = _ref2.triggerConnectionClosure,
triggerConnectionClosure = _ref2$triggerConnecti === void 0 ? 0 : _ref2$triggerConnecti,
_ref2$closeSignalConn = _ref2.closeSignalConnection,
closeSignalConnection = _ref2$closeSignalConn === void 0 ? null : _ref2$closeSignalConn,
_ref2$webRTSPIdleTime = _ref2.webRTSPIdleTimeLimit,
webRTSPIdleTimeLimit = _ref2$webRTSPIdleTime === void 0 ? 5000 : _ref2$webRTSPIdleTime,
_ref2$useRTSPToWebCon = _ref2.useRTSPToWebConnection,
useRTSPToWebConnection = _ref2$useRTSPToWebCon === void 0 ? false : _ref2$useRTSPToWebCon,
_ref2$enableLogging = _ref2.enableLogging,
enableLogging = _ref2$enableLogging === void 0 ? false : _ref2$enableLogging,
_ref2$loadingComponen = _ref2.loadingComponent,
loadingComponent = _ref2$loadingComponen === void 0 ? null : _ref2$loadingComponen,
_ref2$errorComponent = _ref2.errorComponent,
errorComponent = _ref2$errorComponent === void 0 ? null : _ref2$errorComponent,
_ref2$onWebRTSPStream = _ref2.onWebRTSPStreamPreparation,
onWebRTSPStreamPreparation = _ref2$onWebRTSPStream === void 0 ? null : _ref2$onWebRTSPStream,
_ref2$onWebRTSPDiscon = _ref2.onWebRTSPDisconnect,
onWebRTSPDisconnect = _ref2$onWebRTSPDiscon === void 0 ? null : _ref2$onWebRTSPDiscon,
_ref2$onWebRTSPStream2 = _ref2.onWebRTSPStreamPlay,
onWebRTSPStreamPlay = _ref2$onWebRTSPStream2 === void 0 ? null : _ref2$onWebRTSPStream2,
_ref2$onWebRTSPStream3 = _ref2.onWebRTSPStreaming,
onWebRTSPStreaming = _ref2$onWebRTSPStream3 === void 0 ? null : _ref2$onWebRTSPStream3,
_ref2$onWebRTSPConnec = _ref2.onWebRTSPConnect,
onWebRTSPConnect = _ref2$onWebRTSPConnec === void 0 ? null : _ref2$onWebRTSPConnec,
_ref2$onWebRTSPIdle = _ref2.onWebRTSPIdle,
onWebRTSPIdle = _ref2$onWebRTSPIdle === void 0 ? null : _ref2$onWebRTSPIdle,
_ref2$onWebRTSPLog = _ref2.onWebRTSPLog,
onWebRTSPLog = _ref2$onWebRTSPLog === void 0 ? null : _ref2$onWebRTSPLog,
_ref2$height = _ref2.height,
height = _ref2$height === void 0 ? 1080 : _ref2$height,
_ref2$width = _ref2.width,
width = _ref2$width === void 0 ? 1280 : _ref2$width;
var _useTimeout = useTimeout(),
schedule = _useTimeout.schedule;
var _useState = useState(false),
_useState2 = _slicedToArray(_useState, 2),
waitingForData = _useState2[0],
setWaitingForData = _useState2[1];
var _useState3 = useState(false),
_useState4 = _slicedToArray(_useState3, 2),
streamPaused = _useState4[0],
setStreamPaused = _useState4[1];
var _useState5 = useState("Connecting"),
_useState6 = _slicedToArray(_useState5, 2),
status = _useState6[0],
setStatus = _useState6[1];
var _useState7 = useState(false),
_useState8 = _slicedToArray(_useState7, 2),
connected = _useState8[0],
setConnected = _useState8[1];
var connectionAttempts = useRef(sessionStorage.getItem("WEBRTSPConnectionAttempts") !== null ? parseFloat(sessionStorage.getItem("WEBRTSPConnectionAttempts")) : 0);
var signalingSocketRef = useRef(null);
var peerConnectionRef = useRef(null);
var _useState9 = useState(rtspURL),
_useState10 = _slicedToArray(_useState9, 2),
currentRTSPURL = _useState10[0],
setCurrentRTSPURL = _useState10[1];
var clientRegistrationProtocol = useRef(null);
var currentViewObserver = useRef();
var currentStreamID = useRef(null);
var currentChannel = useRef(0);
var playingStream = useRef(false);
var connecting = useRef(false);
var videoRef = useRef(null);
var webRTSPStreaming = useIdleDetection(function () {
if (streamPaused) {
log("log", enableLogging, onWebRTSPLog, "WEBRTSP Connection ~ Reconnection prevented; stream paused.");
return;
}
if (connecting.current) {
log("log", enableLogging, onWebRTSPLog, "WEBRTSP Connection ~ Connection in progress....");
return;
}
if (!connected || preventSignalConnections) {
schedule(function () {
if (connected || playingStream.current) {
return;
}
startCountdown();
}, reconnectionInterval || 2869);
return;
}
if (restartStreamOnIdle && !useRTSPToWebConnection) {
closeWebRTSPConnection(true);
sessionStorage.setItem("WEBRTSPConnected", false);
connecting.current = true;
setConnected(false);
log("log", enableLogging, onWebRTSPLog, "WEBRTSP Connection ~ Reconnecting to ".concat(rtspURL, "..."));
connectToSignalingServer();
}
if (restartStreamOnIdle && useRTSPToWebConnection) {
log("log", enableLogging, onWebRTSPLog, "WEBRTSP Connection ~ ".concat(rtspURL, " unresponsive."));
sessionStorage.setItem("WEBRTSPConnected", false);
connecting.current = true;
setConnected(false);
if (connectionAttempts.current <= 0) {
setStatus("Unresponsive");
}
schedule(function () {
startCountdown();
}, 1269);
}
if (onWebRTSPIdle) {
onWebRTSPIdle(sessionID, status, connected, waitingForData, connectionAttempts);
}
}, webRTSPIdleTimeLimit);
var closeWebRTSPConnection = useCallback( /*#__PURE__*/_asyncToGenerator( /*#__PURE__*/_regeneratorRuntime.mark(function _callee2() {
var omitConnectionClosure,
_args2 = arguments;
return _regeneratorRuntime.wrap(function _callee2$(_context2) {
while (1) switch (_context2.prev = _context2.next) {
case 0:
omitConnectionClosure = _args2.length > 0 && _args2[0] !== undefined ? _args2[0] : false;
if (!(!omitConnectionClosure && triggerConnectionClosure === 0)) {
_context2.next = 3;
break;
}
return _context2.abrupt("return");
case 3:
clearVideoSRC();
if (signalingSocketRef.current) {
signalingSocketRef.current.close();
signalingSocketRef.current = null;
}
closePeerConnection(peerConnectionRef.current);
log("log", enableLogging, onWebRTSPLog, "WEBRTSP Connection ~ Disconnected from source ~ ".concat(rtspURL, "."));
case 7:
case "end":
return _context2.stop();
}
}, _callee2);
})), [triggerConnectionClosure, closePeerConnection]);
var updateRetryDisplay = useCallback(function (remainingTime) {
var connectionT = "".concat(remainingTime.seconds, ":").concat(remainingTime.milliseconds);
setStatus(connectionAttempts.current >= 30 ? "Retrying connection in ".concat(connectionT, " ~ ").concat(connectionAttempts.current, ": possibly offline") : "Retrying connection in ".concat(connectionT, " ~ ").concat(connectionAttempts.current));
}, []);
var onVideoTimeUpdate = useCallback(function (seekEvent) {
var video = videoRef.current;
webRTSPStreaming();
if (video && video.currentTime === 0) {
setStatus("Preparing");
if (onWebRTSPStreamPreparation) {
onWebRTSPStreamPreparation(status, connected, playingStream);
}
return;
}
}, [videoRef]);
var _Countdown = Countdown(idleReconnectionInterval, function () {
if (preventSignalConnections) {
setStatus("No Signal");
return;
}
connectionAttempts.current += 1;
if (!useRTSPToWebConnection) {
connectToSignalingServer();
return;
}
launchRTSPToWebStreams();
}, updateRetryDisplay),
remainingTime = _Countdown.remainingTime,
completed = _Countdown.completed,
startCountdown = _Countdown.startCountdown,
stopCountdown = _Countdown.stopCountdown,
resetCountdown = _Countdown.resetCountdown;
var connectToSignalingServer = function connectToSignalingServer() {
if (useRTSPToWebConnection || HUDOperationsUtilityManager.checkOperation("".concat(sessionID, " >> Connecting to WebRTSP session ~ ").concat(rtspURL)) && connected && rtspURL === null || preventSignalConnections) {
return;
}
connecting.current = true;
var currentUrl = rtspURL;
setStatus("Connecting");
if (signalingSocketRef.current) {
signalingSocketRef.current.close();
}
var signalingSocket = new WebSocket(signalURL);
signalingSocketRef.current = signalingSocket;
signalingSocket.onopen = function () {
if (currentUrl !== rtspURL || preventSignalConnections) {
signalingSocket.close();
return;
}
log("log", enableLogging, onWebRTSPLog, "WEBRTSP Connection ~ Connected to source!");
connecting.current = false;
setStatus("Preparing");
stopCountdown();
initializePeerConnection();
if (!clientRegistrationProtocol.current) {
clientRegistrationProtocol.current = setInterval(function () {
signalingSocket.send(JSON.stringify({
type: "register-client",
sessionID: sessionID,
rtspURL: rtspURL,
clientDetails: clientDetails
}));
}, 1000);
}
if (onWebRTSPConnect) {
onWebRTSPConnect(sessionID, rtspURL, clientDetails, playingStream);
}
};
signalingSocket.onmessage = /*#__PURE__*/function () {
var _ref4 = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime.mark(function _callee8(message) {
var socketMessageProtocols, data;
return _regeneratorRuntime.wrap(function _callee8$(_context8) {
while (1) switch (_context8.prev = _context8.next) {
case 0:
socketMessageProtocols = {
"stream-connection-error": function () {
var _streamConnectionError = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime.mark(function _callee3(data) {
return _regeneratorRuntime.wrap(function _callee3$(_context3) {
while (1) switch (_context3.prev = _context3.next) {
case 0:
setStatus("Connection stalling...Retrying stream...");
playingStream.current = false;
_context3.next = 4;
return Delay(1269);
case 4:
startCountdown();
case 5:
case "end":
return _context3.stop();
}
}, _callee3);
}));
function streamConnectionError(_x9) {
return _streamConnectionError.apply(this, arguments);
}
return streamConnectionError;
}(),
"stream-error": function () {
var _streamError = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime.mark(function _callee4(data) {
return _regeneratorRuntime.wrap(function _callee4$(_context4) {
while (1) switch (_context4.prev = _context4.next) {
case 0:
setStatus("Stream encountered an error...Retrying stream...");
playingStream.current = false;
_context4.next = 4;
return Delay(1269);
case 4:
startCountdown();
case 5:
case "end":
return _context4.stop();
}
}, _callee4);
}));
function streamError(_x10) {
return _streamError.apply(this, arguments);
}
return streamError;
}(),
"stream-exited": function () {
var _streamExited = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime.mark(function _callee5(data) {
return _regeneratorRuntime.wrap(function _callee5$(_context5) {
while (1) switch (_context5.prev = _context5.next) {
case 0:
playingStream.current = false;
schedule(function () {
setStatus("Stream exited");
}, 869);
schedule(function () {
startCountdown();
}, 1269);
case 3:
case "end":
return _context5.stop();
}
}, _callee5);
}));
function streamExited(_x11) {
return _streamExited.apply(this, arguments);
}
return streamExited;
}(),
"client-registration-acknowledged": function clientRegistrationAcknowledged() {
if (clientRegistrationProtocol.current) {
clearInterval(clientRegistrationProtocol.current);
clientRegistrationProtocol.current = null;
createAndSendOffer();
}
},
"candidate": function () {
var _candidate = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime.mark(function _callee6(data) {
var candidate;
return _regeneratorRuntime.wrap(function _callee6$(_context6) {
while (1) switch (_context6.prev = _context6.next) {
case 0:
log("log", enableLogging, onWebRTSPLog, "WEBRTSP Connection ~ Received ICE candidate!");
candidate = new RTCIceCandidate(data.candidate);
_context6.next = 4;
return peerConnectionRef.current.addIceCandidate(candidate);
case 4:
case "end":
return _context6.stop();
}
}, _callee6);
}));
function candidate(_x12) {
return _candidate.apply(this, arguments);
}
return candidate;
}(),
"answer": function () {
var _answer = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime.mark(function _callee7(data) {
var remoteDesc;
return _regeneratorRuntime.wrap(function _callee7$(_context7) {
while (1) switch (_context7.prev = _context7.next) {
case 0:
log("log", enableLogging, onWebRTSPLog, "WEBRTSP Connection ~ Received SDP answer!");
setStatus("Preparing");
remoteDesc = new RTCSessionDescription(data);
_context7.next = 5;
return peerConnectionRef.current.setRemoteDescription(remoteDesc);
case 5:
case "end":
return _context7.stop();
}
}, _callee7);
}));
function answer(_x13) {
return _answer.apply(this, arguments);
}
return answer;
}()
};
data = JSON.parse(message.data);
if (data.type && socketMessageProtocols[data.type]) {
socketMessageProtocols[data.type](data);
}
case 3:
case "end":
return _context8.stop();
}
}, _callee8);
}));
return function (_x8) {
return _ref4.apply(this, arguments);
};
}();
signalingSocket.onerror = function (error) {
if (preventSignalConnections) {
signalingSocket.close();
return;
}
log("error", enableLogging, onWebRTSPLog, "WEBRTSP: Error: ", error);
playingStream.current = false;
setStatus("error");
startCountdown();
};
signalingSocket.onclose = function () {
log("log", enableLogging, onWebRTSPLog, "WEBRTSCP Connection ~ Disconnected from source.");
if (videoRef.current) {
videoRef.current.srcObject = null;
}
playingStream.current = false;
connecting.current = true;
if (preventSignalConnections) {
setStatus("No Signal");
return;
}
setStatus("Connecting");
setConnected(false);
if (triggerConnectionClosure === 0) {
schedule(function () {
if (!connecting.current || playingStream.current) {
return;
}
startCountdown();
}, reconnectionInterval || 2869);
}
if (onWebRTSPDisconnect) {
onWebRTSPDisconnect(sessionID, rtspURL, clientDetails);
}
};
connecting.current = true;
setStatus("loading");
};
var createAndSendOffer = useCallback( /*#__PURE__*/_asyncToGenerator( /*#__PURE__*/_regeneratorRuntime.mark(function _callee9() {
var offer;
return _regeneratorRuntime.wrap(function _callee9$(_context9) {
while (1) switch (_context9.prev = _context9.next) {
case 0:
if (!HUDOperationsUtilityManager.checkOperation("".concat(sessionID, " >> Sending offer to WebRTSP source ~ ").concat(rtspURL))) {
_context9.next = 2;
break;
}
return _context9.abrupt("return");
case 2:
_context9.next = 4;
return peerConnectionRef.current.createOffer({
offerToReceiveVideo: true
});
case 4:
offer = _context9.sent;
_context9.next = 7;
return peerConnectionRef.current.setLocalDescription(offer);
case 7:
try {
signalingSocketRef.current.send(JSON.stringify({
type: "offer",
sdp: peerConnectionRef.current.localDescription.sdp,
config: {
clientStreamConfigurations: clientStreamSettings,
frameHeight: height,
frameWidth: width,
clientDetails: clientDetails,
rtspURL: rtspURL
}
}));
} catch (error) {}
case 8:
case "end":
return _context9.stop();
}
}, _callee9);
})), [rtspURL, height, width]);
var initializePeerConnection = useCallback(function () {
if (HUDOperationsUtilityManager.checkOperation("".concat(sessionID, " >> Initializing peer connection in WebRTSP session ~ ").concat(rtspURL))) {
return;
}
var peerConnection = new RTCPeerConnection({
iceServers: [{
urls: "stun:stun.l.google.com:19302"
}]
});
peerConnection.ontrack = function (event) {
log("log", enableLogging, onWebRTSPLog, "WEBRTSP Media ~ Received remote track!");
var track = event.track;
setStatus("streaming");
if (videoRef.current && videoRef.current.srcObject == null) {
var remoteStream = new MediaStream();
remoteStream.addTrack(track);
videoRef.current.srcObject = remoteStream;
}
};
peerConnection.oniceconnectionstatechange = function () {
log("log", enableLogging, onWebRTSPLog, "Connection state ~ ", peerConnection.iceConnectionState);
};
peerConnection.onicecandidate = function (event) {
if (event.candidate) {
setStatus("Preparing");
try {
signalingSocketRef.current.send(JSON.stringify({
type: "candidate",
candidate: event.candidate
}));
} catch (error) {}
}
};
peerConnectionRef.current = peerConnection;
}, [sessionID, rtspURL]);
var launchRTSPToWebStreams = useCallback( /*#__PURE__*/_asyncToGenerator( /*#__PURE__*/_regeneratorRuntime.mark(function _callee10() {
var streamDetails;
return _regeneratorRuntime.wrap(function _callee10$(_context10) {
while (1) switch (_context10.prev = _context10.next) {
case 0:
_context10.next = 2;
return getRTSPToWebStreamDetails(signalURL, streamsURL, signalName, signalID);
case 2:
streamDetails = _context10.sent;
if (!(!streamDetails || !streamDetails[rtspURL])) {
_context10.next = 6;
break;
}
log("log", enableLogging, onWebRTSPLog, "Stream details not found for ~ ".concat(rtspURL));
return _context10.abrupt("return");
case 6:
_context10.next = 8;
return closeWebRTSPConnection(true);
case 8:
addVideoEvents();
currentStreamID.current = streamDetails[rtspURL].streamID;
currentChannel.current = streamDetails[rtspURL].channel;
_context10.next = 13;
return startStream(signalURL, streamsURL, streamDetails[rtspURL].streamID, streamDetails[rtspURL].channel, videoRef, peerConnectionRef, startCountdown, stopCountdown, setConnected, connecting, webRTSPStreaming, enableLogging, onWebRTSPLog, function () {
log("log", enableLogging, onWebRTSPLog, "WEBRTSP ~ Preparing stream ~ ".concat(rtspURL, "."));
setStatus("Preparing");
if (onWebRTSPConnect) {
onWebRTSPConnect(sessionID, rtspURL, clientDetails, streamDetails[rtspURL].streamID, streamDetails[rtspURL].channel, playingStream);
}
});
case 13:
case "end":
return _context10.stop();
}
}, _callee10);
})), [signalURL, streamsURL, rtspURL, signalName, signalID, enableLogging]);
var clearVideoEvents = useCallback(function () {
if (videoRef.current) {
videoRef.current.removeEventListener("timeupdate", onVideoTimeUpdate);
videoRef.current.removeEventListener("playing", onPlaying);
videoRef.current.removeEventListener("stalled", onStalled);
videoRef.current.removeEventListener("pause", onPause);
videoRef.current.removeEventListener("ended", onEnded);
videoRef.current.removeEventListener("play", onPlay);
}
}, [videoRef]);
var clearVideoSRC = useCallback(function () {
if (videoRef.current && videoRef.current.srcObject) {
var oldStream = videoRef.current.srcObject;
oldStream.getTracks().forEach(function (track) {
return track.stop();
});
videoRef.current.srcObject = null;
playingStream.current = false;
if (onWebRTSPStreaming) {
onWebRTSPStreaming(status, connected, playingStream);
}
}
}, []);
var addVideoEvents = useCallback(function () {
if (videoRef.current) {
videoRef.current.addEventListener("timeupdate", onVideoTimeUpdate);
videoRef.current.addEventListener("playing", onPlaying);
videoRef.current.addEventListener("stalled", onStalled);
videoRef.current.addEventListener("pause", onPause);
videoRef.current.addEventListener("ended", onEnded);
videoRef.current.addEventListener("play", onPlay);
}
}, []);
var disconnectStream = useCallback(function () {
setStreamPaused(true);
closeWebRTSPConnection(true);
}, []);
var resumeStream = useCallback( /*#__PURE__*/_asyncToGenerator( /*#__PURE__*/_regeneratorRuntime.mark(function _callee11() {
return _regeneratorRuntime.wrap(function _callee11$(_context11) {
while (1) switch (_context11.prev = _context11.next) {
case 0:
setStreamPaused(false);
launchRTSPToWebStreams();
case 2:
case "end":
return _context11.stop();
}
}, _callee11);
})), []);
var onPlaying = useCallback(function () {
log("log", enableLogging, onWebRTSPLog, "WEBRTSP: ".concat(rtspURL, " streaming."));
sessionStorage.setItem("WEBRTSPConnectionAttempts", 0);
sessionStorage.setItem("WEBRTSPConnected", true);
connectionAttempts.current = 0;
playingStream.current = true;
setStatus("streaming");
webRTSPStreaming();
setConnected(true);
if (onWebRTSPStreaming) {
onWebRTSPStreaming(status, connected, playingStream);
}
}, [setConnected, connectionAttempts]);
var onStalled = useCallback(function () {
log("log", enableLogging, onWebRTSPLog, "WEBRTSP: ".concat(rtspURL, " stalling."));
setStatus("Idle");
schedule(function () {
startCountdown();
}, 1269);
}, [connectionAttempts]);
var onPause = useCallback(function () {
log("log", enableLogging, onWebRTSPLog, "WEBRTSP: ".concat(rtspURL, " idle."));
setStatus("Idle");
}, [connectionAttempts]);
var onEnded = useCallback(function () {
log("log", enableLogging, onWebRTSPLog, "WEBRTSP: ".concat(rtspURL, " exited."));
setStatus("Stream exited...");
schedule(function () {
startCountdown();
}, 1269);
}, [connectionAttempts]);
var onPlay = useCallback(function () {
log("log", enableLogging, onWebRTSPLog, "WEBRTSP: ".concat(rtspURL, " starting."));
setStatus("Connecting");
webRTSPStreaming();
if (onWebRTSPStreamPlay) {
onWebRTSPStreamPlay(status, connected, playingStream);
}
}, [setStatus]);
var checkVisibilityOnLoad = useCallback(function () {
if (videoRef.current) {
var rect = videoRef.current.getBoundingClientRect();
var viewerVisible = rect.top < window.innerHeight && rect.bottom > 0 && rect.left < window.innerWidth && rect.right > 0;
if (viewerVisible) {
resumeStream();
return;
}
disconnectStream();
}
}, [disconnectStream, resumeStream]);
var viewerAutoDisconnector = useCallback(function (entries) {
entries.forEach(function (entry) {
if (!autoDisconnectsWhenHidden) {
return;
}
if (entry.isIntersecting) {
resumeStream();
} else {
disconnectStream();
}
});
}, [disconnectStream, resumeStream, autoDisconnectsWhenHidden]);
useEffect(function () {
if (useRTSPToWebConnection || HUDOperationsUtilityManager.checkOperation("".concat(sessionID, " >> Loading RTSC ~ ").concat(rtspURL)) || preventSignalConnections) {
return;
}
if (closeSignalConnection) {
closeSignalConnection.current = closeWebRTSPConnection;
}
closeWebRTSPConnection(true);
connectToSignalingServer();
addVideoEvents();
return function () {
closeWebRTSPConnection(true);
clearVideoEvents();
};
}, [signalURL, rtspURL, width, height, useRTSPToWebConnection, preventSignalConnections]);
useEffect(function () {
if (!useRTSPToWebConnection || HUDOperationsUtilityManager.checkOperation("".concat(sessionID, " >> Loading RTSC ~ ").concat(rtspURL))) {
return;
}
if (closeSignalConnection) {
closeSignalConnection.current = closeWebRTSPConnection;
}
connecting.current = true;
setStatus("Connecting");
launchRTSPToWebStreams();
return function () {
closeWebRTSPConnection(true);
clearVideoEvents();
};
}, [useRTSPToWebConnection, signalURL, signalName, signalID, rtspURL, preventSignalConnections]);
useEffect(function () {
var _videoRef$current;
if (!autoDisconnectsWhenHidden) {
return;
}
currentViewObserver.current = new IntersectionObserver(viewerAutoDisconnector, {
threshold: autoDisconnectThreshold
});
var element = (_videoRef$current = videoRef.current) === null || _videoRef$current === void 0 ? void 0 : _videoRef$current.parentElement;
if (element) {
currentViewObserver.current.observe(element);
checkVisibilityOnLoad();
}
return function () {
if (currentViewObserver.current) {
currentViewObserver.current.disconnect();
}
};
}, [viewerAutoDisconnector, checkVisibilityOnLoad, autoDisconnectsWhenHidden, autoDisconnectThreshold]);
useEffect(function () {
if (triggerConnectionClosure === 0) {
return;
}
closeWebRTSPConnection(false);
}, [triggerConnectionClosure]);
useEffect(function () {
if (!preventSignalConnections) {
return;
}
closeWebRTSPConnection(true);
setStatus("No Signal");
}, [preventSignalConnections]);
return /*#__PURE__*/React.createElement("div", _extends({
style: _objectSpread(_objectSpread({}, styles.container), containerConfigurationSettings)
}, containerConfigurations), /*#__PURE__*/React.createElement("style", null, keyframes), /*#__PURE__*/React.createElement("div", {
style: _objectSpread(_objectSpread({}, styles.videoContainer), videoContainerConfigurationSettings)
}, status !== "streaming" && status !== "error" && status !== "Idle" && status !== "No Signal" && /*#__PURE__*/React.createElement("div", {
style: _objectSpread(_objectSpread({}, styles.overlay), overlayConfigurationSettings)
}, /*#__PURE__*/React.createElement("div", {
style: _objectSpread(_objectSpread({}, styles.actionContainer), actionContainerConfigurationSettings)
}, loadingComponent ? loadingComponent : /*#__PURE__*/React.createElement("div", {
style: _objectSpread(_objectSpread({}, styles.loadingSpinner), loadingSpinnerConfigurationSettings)
}), /*#__PURE__*/React.createElement("div", {
style: _objectSpread(_objectSpread({}, styles.message), messageConfigurationSettings)
}, "".concat(status, "...")))), status === "No Signal" && /*#__PURE__*/React.createElement("div", {
style: _objectSpread(_objectSpread({}, styles.overlay), overlayConfigurationSettings)
}, /*#__PURE__*/React.createElement("div", {
style: _objectSpread(_objectSpread({}, styles.actionContainer), actionContainerConfigurationSettings)
}, loadingComponent ? loadingComponent : /*#__PURE__*/React.createElement("div", {
style: _objectSpread(_objectSpread({}, styles.loadingSpinner), loadingSpinnerConfigurationSettings)
}), /*#__PURE__*/React.createElement("div", {
style: _objectSpread(_objectSpread({}, styles.message), messageConfigurationSettings)
}, status))), waitingForData && status === "streaming" && /*#__PURE__*/React.createElement("div", {
style: _objectSpread(_objectSpread({}, styles.overlay), {}, {
backgroundColor: "rgba(0, 0, 0, 0.169)"
}, overlayConfigurationSettings)
}, /*#__PURE__*/React.createElement("div", {
style: _objectSpread(_objectSpread({}, styles.actionContainer), actionContainerConfigurationSettings)
}, loadingComponent ? loadingComponent : /*#__PURE__*/React.createElement("div", {
style: _objectSpread(_objectSpread({}, styles.loadingSpinner), loadingSpinnerConfigurationSettings)
}), /*#__PURE__*/React.createElement("div", {
style: _objectSpread(_objectSpread({}, styles.message), messageConfigurationSettings)
}, "Idle..."))), /*#__PURE__*/React.createElement("video", {
ref: videoRef,
style: _objectSpread(_objectSpread(_objectSpread({}, styles.video), videoConfigurationSettings), {}, {
visibility: status === "streaming" || status === "Idle" || status === "Unresponsive" ? "visible" : "hidden"
}),
playsInline: true,
autoPlay: true,
muted: true,
onError: ( /*#__PURE__*/function () {
var _ref8 = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime.mark(function _callee12(e) {
return _regeneratorRuntime.wrap(function _callee12$(_context12) {
while (1) switch (_context12.prev = _context12.next) {
case 0:
log("error", enableLogging, onWebRTSPLog, "Video error ~ ".concat(e));
playingStream.current = false;
setStatus("error");
case 3:
case "end":
return _context12.stop();
}
}, _callee12);
}));
return function (_x14) {
return _ref8.apply(this, arguments);
};
}())
}), status === "error" && /*#__PURE__*/React.createElement("div", {
style: _objectSpread(_objectSpread({}, styles.overlay), overlayConfigurationSettings)
}, /*#__PURE__*/React.createElement("div", {
style: _objectSpread(_objectSpread({}, styles.actionContainer), actionContainerConfigurationSettings)
}, errorComponent && errorComponent, /*#__PURE__*/React.createElement("div", {
style: _objectSpread(_objectSpread({}, styles.message), messageConfigurationSettings)
}, "Error occurred during playback.")))));
}
;
HUDRTSCViewer.propTypes = {
actionContainerConfigurationSettings: PropTypes.object,
videoContainerConfigurationSettings: PropTypes.object,
loadingSpinnerConfigurationSettings: PropTypes.object,
containerConfigurationSettings: PropTypes.object,
messageConfigurationSettings: PropTypes.object,
overlayConfigurationSettings: PropTypes.object,
videoConfigurationSettings: PropTypes.object,
signalURL: PropTypes.string,
rtspURL: PropTypes.string,
height: PropTypes.string,
width: PropTypes.string
};
export default HUDRTSCViewer;