vcs-controller/ui/static/rtc.js

91 lines
2.4 KiB
JavaScript
Raw Normal View History

2024-07-31 19:42:30 -07:00
2024-08-17 13:11:59 -07:00
2024-08-23 18:35:19 -07:00
import { event } from "./@tauri-apps/api/index.js";
2024-07-31 19:42:30 -07:00
2024-08-23 18:35:19 -07:00
async function rtc_init() {
console.log("ding ding!");
console.log(event);
const videoview = document.getElementById("remoteview");
const config = {
iceServers: [{ urls: "stun:localhost" }]
};
const polite = true;
2024-07-31 19:42:30 -07:00
2024-08-23 18:35:19 -07:00
const pc = new RTCPeerConnection(config);
pc.ontrack = ({ track, streams }) => {
track.onunmute = () => {
if (remoteview.srcObject) {
return;
}
remoteview.srcObject = streams[0];
};
};
2024-07-31 19:42:30 -07:00
2024-08-23 18:35:19 -07:00
let makingOffer = false;
pc.onnegotionationneeded = async () => {
try {
makingOffer = true;
await pc.setLocalDescription();
event.emit("webrtc-message", { description: pc.localDescription });
} catch (err) {
console.error(err);
} finally {
makingOffer = false;
}
};
pc.onicecandidate = ({ candidate }) => event.emit("webrtc-message", { candidate });
pc.oniceconnectionstatechange = () => {
if (pc.iceConnectionState === "failed") {
pc.restartIce();
2024-07-31 19:42:30 -07:00
}
};
2024-08-17 13:11:59 -07:00
2024-08-23 18:35:19 -07:00
let ignoreOffer = false;
2024-08-17 13:11:59 -07:00
2024-08-23 18:35:19 -07:00
console.log("registering listner");
const application_message = await event.listen('frontend_message', async (event) => {
console.log("Event: ");
console.log(event);
2024-07-31 19:42:30 -07:00
2024-08-23 18:35:19 -07:00
const { description, candidate } = event.payload.data;
2024-07-31 19:42:30 -07:00
2024-08-23 18:35:19 -07:00
try {
if (description) {
const offerCollision =
description.type === "offer" &&
(makingOffer || pc.signalingState !== "stable");
2024-07-31 19:42:30 -07:00
2024-08-23 18:35:19 -07:00
ignoreOffer = !polite && offerCollision;
if (ignoreOffer) {
return;
}
await pc.setRemoteDescription(description);
if (description.type === "offer") {
await pc.setLocalDescription();
event.emit( "webrtc-message", { description: pc.localDescription });
}
} else if (candidate) {
try {
await pc.addIceCandidate(candidate);
} catch (err) {
if (!ignoreOffer) {
throw err;
}
2024-07-31 19:42:30 -07:00
}
}
2024-08-23 18:35:19 -07:00
} catch (err) {
console.error(err);
2024-07-31 19:42:30 -07:00
}
2024-08-23 18:35:19 -07:00
});
}
2024-08-22 21:02:08 -07:00
2024-08-23 18:35:19 -07:00
export { rtc_init };