kvmevt.js 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415
  1. /*
  2. kvmevt.js
  3. Keyboard, Video, Mouse (KVM) over WebSocket client-side event handling.
  4. Handles mouse and keyboard events, sending them to the server via WebSocket.
  5. Also manages audio streaming from the server.
  6. */
  7. const enableKvmEventDebugPrintout = false; //Set to true to enable debug printout
  8. const cursorCaptureElementId = "remoteCapture";
  9. let hidsocket;
  10. let hidWebSocketReady = false;
  11. let protocol = window.location.protocol === 'https:' ? 'wss' : 'ws';
  12. let port = window.location.port ? window.location.port : (protocol === 'wss' ? 443 : 80);
  13. let hidSocketURL = `${protocol}://${window.location.hostname}:${port}/api/v1/hid/{uuid}/events`;
  14. let audioSocketURL = `${protocol}://${window.location.hostname}:${port}/api/v1/stream/{uuid}/audio`;
  15. let mouseMoveAbsolute = true; // Set to true for absolute mouse coordinates, false for relative
  16. let mouseIsOutside = false; //Mouse is outside capture element
  17. let audioFrontendStarted = false; //Audio frontend has been started
  18. let kvmDeviceUUID = ""; //UUID of the device being controlled
  19. if (window.location.hash.length > 1){
  20. kvmDeviceUUID = window.location.hash.substring(1);
  21. hidSocketURL = hidSocketURL.replace("{uuid}", kvmDeviceUUID);
  22. audioSocketURL = audioSocketURL.replace("{uuid}", kvmDeviceUUID);
  23. massStorageSwitchURL = massStorageSwitchURL.replace("{uuid}", kvmDeviceUUID);
  24. //Start HID WebSocket
  25. startHidWebSocket();
  26. setStreamingSource(kvmDeviceUUID);
  27. }
  28. /* Initiate API endpoint */
  29. function setStreamingSource(deviceUUID) {
  30. let videoStreamURL = `/api/v1/stream/${deviceUUID}/video`
  31. let videoElement = document.getElementById("remoteCapture");
  32. videoElement.src = videoStreamURL;
  33. }
  34. /* Mouse events */
  35. function handleMouseMove(event) {
  36. const hidCommand = {
  37. event: 2,
  38. mouse_x: event.clientX,
  39. mouse_y: event.clientY,
  40. };
  41. const rect = event.target.getBoundingClientRect();
  42. const relativeX = event.clientX - rect.left;
  43. const relativeY = event.clientY - rect.top;
  44. if (relativeX < 0 || relativeY < 0 || relativeX > rect.width || relativeY > rect.height) {
  45. mouseIsOutside = true;
  46. return; // Mouse is outside the client rect
  47. }
  48. mouseIsOutside = false;
  49. const percentageX = (relativeX / rect.width) * 4096;
  50. const percentageY = (relativeY / rect.height) * 4096;
  51. hidCommand.mouse_x = Math.round(percentageX);
  52. hidCommand.mouse_y = Math.round(percentageY);
  53. if (enableKvmEventDebugPrintout) {
  54. console.log(`Mouse move: (${event.clientX}, ${event.clientY})`);
  55. console.log(`Mouse move relative: (${relativeX}, ${relativeY})`);
  56. console.log(`Mouse move percentage: (${hidCommand.mouse_x}, ${hidCommand.mouse_y})`);
  57. }
  58. if (hidsocket && hidsocket.readyState === WebSocket.OPEN) {
  59. hidsocket.send(JSON.stringify(hidCommand));
  60. } else {
  61. console.error("WebSocket is not open.");
  62. }
  63. }
  64. function handleMousePress(event) {
  65. event.preventDefault();
  66. event.stopImmediatePropagation();
  67. if (mouseIsOutside) {
  68. console.warn("Mouse is outside the capture area, ignoring mouse press.");
  69. return;
  70. }
  71. /* Mouse buttons: 1=left, 2=right, 3=middle */
  72. const buttonMap = {
  73. 0: 1,
  74. 1: 3,
  75. 2: 2
  76. }; //Map javascript mouse buttons to HID buttons
  77. const hidCommand = {
  78. event: 3,
  79. mouse_button: buttonMap[event.button] || 0
  80. };
  81. // Log the mouse button state
  82. if (enableKvmEventDebugPrintout) {
  83. console.log(`Mouse down: ${hidCommand.mouse_button}`);
  84. }
  85. if (hidsocket && hidsocket.readyState === WebSocket.OPEN) {
  86. hidsocket.send(JSON.stringify(hidCommand));
  87. } else {
  88. console.error("WebSocket is not open.");
  89. }
  90. if (!audioFrontendStarted){
  91. startAudioWebSocket();
  92. audioFrontendStarted = true;
  93. }
  94. }
  95. function handleMouseRelease(event) {
  96. event.preventDefault();
  97. event.stopImmediatePropagation();
  98. if (mouseIsOutside) {
  99. console.warn("Mouse is outside the capture area, ignoring mouse press.");
  100. return;
  101. }
  102. /* Mouse buttons: 1=left, 2=right, 3=middle */
  103. const buttonMap = {
  104. 0: 1,
  105. 1: 3,
  106. 2: 2
  107. }; //Map javascript mouse buttons to HID buttons
  108. const hidCommand = {
  109. event: 4,
  110. mouse_button: buttonMap[event.button] || 0
  111. };
  112. if (enableKvmEventDebugPrintout) {
  113. console.log(`Mouse release: ${hidCommand.mouse_button}`);
  114. }
  115. if (hidsocket && hidsocket.readyState === WebSocket.OPEN) {
  116. hidsocket.send(JSON.stringify(hidCommand));
  117. } else {
  118. console.error("WebSocket is not open.");
  119. }
  120. }
  121. function handleMouseScroll(event) {
  122. const hidCommand = {
  123. event: 5,
  124. mouse_scroll: event.deltaY
  125. };
  126. if (mouseIsOutside) {
  127. console.warn("Mouse is outside the capture area, ignoring mouse press.");
  128. return;
  129. }
  130. if (enableKvmEventDebugPrintout) {
  131. console.log(`Mouse scroll: mouse_scroll=${event.deltaY}`);
  132. }
  133. if (hidsocket && hidsocket.readyState === WebSocket.OPEN) {
  134. hidsocket.send(JSON.stringify(hidCommand));
  135. } else {
  136. console.error("WebSocket is not open.");
  137. }
  138. }
  139. /* Keyboard */
  140. function isNumpadEvent(event) {
  141. return event.location === 3;
  142. }
  143. function handleKeyDown(event) {
  144. event.preventDefault();
  145. event.stopImmediatePropagation();
  146. const key = event.key;
  147. let hidCommand = {
  148. event: 0,
  149. keycode: event.keyCode
  150. };
  151. if (enableKvmEventDebugPrintout) {
  152. console.log(`Key down: ${key} (code: ${event.keyCode})`);
  153. }
  154. // Check if the key is a modkey on the right side of the keyboard
  155. const rightModKeys = ['Control', 'Alt', 'Shift', 'Meta'];
  156. if (rightModKeys.includes(key) && event.location === 2) {
  157. hidCommand.is_right_modifier_key = true;
  158. }else if (key === 'Enter' && isNumpadEvent(event)) {
  159. //Special case for Numpad Enter
  160. hidCommand.is_right_modifier_key = true;
  161. }else{
  162. hidCommand.is_right_modifier_key = false;
  163. }
  164. if (hidsocket && hidsocket.readyState === WebSocket.OPEN) {
  165. hidsocket.send(JSON.stringify(hidCommand));
  166. } else {
  167. console.error("WebSocket is not open.");
  168. }
  169. }
  170. function handleKeyUp(event) {
  171. event.preventDefault();
  172. event.stopImmediatePropagation();
  173. const key = event.key;
  174. let hidCommand = {
  175. event: 1,
  176. keycode: event.keyCode
  177. };
  178. if (enableKvmEventDebugPrintout) {
  179. console.log(`Key up: ${key} (code: ${event.keyCode})`);
  180. }
  181. // Check if the key is a modkey on the right side of the keyboard
  182. const rightModKeys = ['Control', 'Alt', 'Shift', 'Meta'];
  183. if (rightModKeys.includes(key) && event.location === 2) {
  184. hidCommand.is_right_modifier_key = true;
  185. } else if (key === 'Enter' && isNumpadEvent(event)) {
  186. //Special case for Numpad Enter
  187. hidCommand.is_right_modifier_key = true;
  188. }else{
  189. hidCommand.is_right_modifier_key = false;
  190. }
  191. if (hidsocket && hidsocket.readyState === WebSocket.OPEN) {
  192. hidsocket.send(JSON.stringify(hidCommand));
  193. } else {
  194. console.error("WebSocket is not open.");
  195. }
  196. }
  197. /* Start and Stop HID events */
  198. function startHidWebSocket(){
  199. if (hidsocket){
  200. //Already started
  201. console.warn("Invalid usage: HID Transport Websocket already started!");
  202. return;
  203. }
  204. const socketUrl = hidSocketURL;
  205. hidsocket = new WebSocket(socketUrl);
  206. hidsocket.addEventListener('open', function(event) {
  207. console.log('HID Transport WebSocket is connected.');
  208. // Send a soft reset command to the server to reset the HID state
  209. // that possibly got out of sync from previous session
  210. const hidResetCommand = {
  211. event: 0xFF
  212. };
  213. hidsocket.send(JSON.stringify(hidResetCommand));
  214. });
  215. hidsocket.addEventListener('message', function(event) {
  216. //Todo: handle control signals from server if needed
  217. //console.log('Message from server ', event.data);
  218. });
  219. }
  220. // Attach keyboard event listeners
  221. const remoteCaptureEle = document.getElementById(cursorCaptureElementId);
  222. document.addEventListener('keydown', handleKeyDown);
  223. document.addEventListener('keyup', handleKeyUp);
  224. // Attach mouse event listeners
  225. remoteCaptureEle.addEventListener('mousemove', handleMouseMove);
  226. remoteCaptureEle.addEventListener('mousedown', handleMousePress);
  227. remoteCaptureEle.addEventListener('mouseup', handleMouseRelease);
  228. remoteCaptureEle.addEventListener('wheel', handleMouseScroll);
  229. function stopWebSocket(){
  230. if (!hidsocket){
  231. alert("No ws connection to stop");
  232. return;
  233. }
  234. hidsocket.close();
  235. console.log('HID Transport WebSocket disconnected.');
  236. document.removeEventListener('keydown', handleKeyDown);
  237. document.removeEventListener('keyup', handleKeyUp);
  238. }
  239. /* Audio Streaming Frontend */
  240. let audioSocket;
  241. let audioContext;
  242. let audioQueue = [];
  243. let audioPlaying = false;
  244. //accept low, standard, high quality audio mode
  245. function startAudioWebSocket(quality="standard") {
  246. if (audioSocket) {
  247. console.warn("Audio WebSocket already started");
  248. return;
  249. }
  250. audioSocket = new WebSocket(`${audioSocketURL}?quality=${quality}`);
  251. audioSocket.binaryType = 'arraybuffer';
  252. audioSocket.onopen = function() {
  253. console.log("Audio WebSocket connected");
  254. if (!audioContext) {
  255. audioContext = new (window.AudioContext || window.webkitAudioContext)({sampleRate: 24000});
  256. }
  257. };
  258. const MAX_AUDIO_QUEUE = 4;
  259. let PCM_SAMPLE_RATE;
  260. if (quality == "high"){
  261. PCM_SAMPLE_RATE = 48000; // Use 48kHz for high quality
  262. } else if (quality == "low") {
  263. PCM_SAMPLE_RATE = 16000; // Use 24kHz for low quality
  264. } else {
  265. PCM_SAMPLE_RATE = 24000; // Default to 24kHz for standard quality
  266. }
  267. let scheduledTime = 0;
  268. audioSocket.onmessage = function(event) {
  269. if (!audioContext) return;
  270. let pcm = new Int16Array(event.data);
  271. if (pcm.length === 0) {
  272. console.warn("Received empty PCM data");
  273. return;
  274. }
  275. if (pcm.length % 2 !== 0) {
  276. console.warn("Received PCM data with odd length, dropping last sample");
  277. pcm = pcm.slice(0, -1);
  278. }
  279. // Convert Int16 PCM to Float32 [-1, 1]
  280. let floatBuf = new Float32Array(pcm.length);
  281. for (let i = 0; i < pcm.length; i++) {
  282. floatBuf[i] = pcm[i] / 32768;
  283. }
  284. // Limit queue size to prevent memory overflow
  285. if (audioQueue.length >= MAX_AUDIO_QUEUE) {
  286. audioQueue.shift();
  287. }
  288. audioQueue.push(floatBuf);
  289. scheduleAudioPlayback();
  290. };
  291. audioSocket.onclose = function() {
  292. console.log("Audio WebSocket closed");
  293. audioSocket = null;
  294. audioPlaying = false;
  295. audioQueue = [];
  296. scheduledTime = 0;
  297. };
  298. audioSocket.onerror = function(e) {
  299. console.error("Audio WebSocket error", e);
  300. };
  301. function scheduleAudioPlayback() {
  302. if (!audioContext || audioQueue.length === 0) return;
  303. // Use audioContext.currentTime to schedule buffers back-to-back
  304. if (scheduledTime < audioContext.currentTime) {
  305. scheduledTime = audioContext.currentTime;
  306. }
  307. while (audioQueue.length > 0) {
  308. let floatBuf = audioQueue.shift();
  309. let frameCount = floatBuf.length / 2;
  310. let buffer = audioContext.createBuffer(2, frameCount, PCM_SAMPLE_RATE);
  311. for (let ch = 0; ch < 2; ch++) {
  312. let channelData = buffer.getChannelData(ch);
  313. for (let i = 0; i < frameCount; i++) {
  314. channelData[i] = floatBuf[i * 2 + ch];
  315. }
  316. }
  317. if (scheduledTime - audioContext.currentTime > 0.2) {
  318. console.warn("Audio buffer too far ahead, discarding frame");
  319. continue;
  320. }
  321. let source = audioContext.createBufferSource();
  322. source.buffer = buffer;
  323. source.connect(audioContext.destination);
  324. source.start(scheduledTime);
  325. scheduledTime += buffer.duration;
  326. }
  327. }
  328. }
  329. function stopAudioWebSocket() {
  330. if (!audioSocket) {
  331. console.warn("No audio WebSocket to stop");
  332. return;
  333. }
  334. if (audioSocket.readyState === WebSocket.OPEN) {
  335. audioSocket.send("exit");
  336. }
  337. audioSocket.onclose = null; // Prevent onclose from being called again
  338. audioSocket.onerror = null; // Prevent onerror from being called again
  339. audioSocket.close();
  340. audioSocket = null;
  341. audioPlaying = false;
  342. audioQueue = [];
  343. if (audioContext) {
  344. audioContext.close();
  345. audioContext = null;
  346. }
  347. }
  348. window.addEventListener('beforeunload', function() {
  349. stopAudioWebSocket();
  350. });