New WebRTC Component Changes

This commit is contained in:
2025-10-02 19:54:58 +05:30
parent c4e868490e
commit f10b6e1314
2 changed files with 172 additions and 103 deletions
+172 -99
View File
@@ -4,6 +4,7 @@ import { cn } from "../utils/cn";
interface Props extends HTMLAttributes<"div"> { interface Props extends HTMLAttributes<"div"> {
streamUrl: string; streamUrl: string;
iceServers?: any[];
poster?: string; poster?: string;
checkStreamFn?: string; checkStreamFn?: string;
retryInterval?: number; retryInterval?: number;
@@ -11,6 +12,7 @@ interface Props extends HTMLAttributes<"div"> {
const { const {
streamUrl, streamUrl,
iceServers = [],
poster, poster,
class: className, class: className,
checkStreamFn, checkStreamFn,
@@ -124,122 +126,193 @@ const {
</div> </div>
</div> </div>
<script> <script type="module" is:inline define:vars={{ streamUrl, iceServers }}>
document.addEventListener("DOMContentLoaded", () => { const videoEl = document.getElementById("live-video");
const videoCardEl = document.getElementById("video-card"); const overlayEl = document.getElementById("overlay");
const videoEl = document.getElementById("live-video"); const volumeBtn = document.getElementById("volume-btn");
const overlayEl = document.getElementById("overlay"); const fullscreenBtn = document.getElementById("fullscreen-btn");
const volumeBtn = document.getElementById("volume-btn");
const fullscreenBtn = document.getElementById("fullscreen-btn");
let player: any; function createWhepPlayer(whepUrl, videoEl, opts = {}) {
let retryTimer: any; const { iceServers = [], onEvent } = opts;
let streamUrl = videoEl?.dataset.stream; let pc = null;
let controller = { stopped: false };
const showOverlay = (msg: string) => { function emit(type, payload) {
overlayEl!.textContent = msg; if (typeof onEvent === "function") onEvent(type, payload);
overlayEl!.classList.add("show"); }
};
const hideOverlay = () => overlayEl!.classList.remove("show");
showOverlay("Connecting to live stream…"); async function start() {
controller.stopped = false;
emit("status", { msg: "starting" });
async function startPlayer() { if (pc) {
try { try {
if (videoEl) pc.close();
player = new window.WebRTCPlayer({ } catch (e) {}
video: videoEl as HTMLVideoElement, pc = null;
type: "whep", }
statsTypeFilter: "^candidate-*|^inbound-rtp",
pc = new RTCPeerConnection({ iceServers });
const remoteStream = new MediaStream();
videoEl.srcObject = remoteStream;
pc.addEventListener("track", (ev) => {
if (ev.streams && ev.streams[0]) {
ev.streams[0]
.getTracks()
.forEach((t) => remoteStream.addTrack(t));
} else {
remoteStream.addTrack(ev.track);
}
emit("track", { kind: ev.track.kind });
});
pc.addEventListener("iceconnectionstatechange", () => {
emit("ice", { state: pc.iceConnectionState });
});
const localCandidates = [];
pc.addEventListener("icecandidate", (e) => {
if (e.candidate) localCandidates.push(e.candidate);
});
const offer = await pc.createOffer({
offerToReceiveAudio: true,
offerToReceiveVideo: true,
});
await pc.setLocalDescription(offer);
await waitForIceGatheringComplete(pc, 10000);
const sdpOffer = pc.localDescription.sdp;
emit("debug", { sdpOfferSnippet: sdpOffer.slice(0, 200) });
emit("status", { msg: "posting offer" });
const res = await fetch(whepUrl, {
method: "POST",
headers: { "Content-Type": "application/sdp" },
body: sdpOffer,
});
if (!res.ok) {
const text = await res.text().catch(() => "<no-body>");
if (res.status == 404)
emit("error", {
msg: `No Stream found !`,
});
else
emit("error", {
msg: `Something went wrong with stream!`,
}); });
player.on("media-recovered", () => { throw new Error("WHEP POST failed: " + res.status);
hideOverlay();
});
player.on("peer-connection-connected", () => {
hideOverlay();
});
player.on("no-media", () => {
showOverlay(
"Stream not started yet or Stream already ended",
);
});
player.on("error", (err: any) => {
showOverlay("Error: " + err.message);
});
await player.load(new URL(streamUrl || ""));
player.unmute();
} catch (err: any) {
showOverlay("Failed to initialize: " + err.message);
} }
}
async function checkAndStart() { const answerSdp = await res.text();
emit("debug", { answerSnippet: answerSdp.slice(0, 200) });
const answer = { type: "answer", sdp: answerSdp };
await pc.setRemoteDescription(answer);
try { try {
const checkStreamFn: any = videoEl.muted = true;
videoCardEl?.dataset.checkStreamFn || ""; await videoEl.play().catch(() => {});
emit("playing", { msg: "playing" });
} catch (err) {
emit("error", { msg: "play failed", err });
}
if (checkStreamFn) { const trackTimer = setTimeout(() => {
const fn: any = window[checkStreamFn]; if (remoteStream.getVideoTracks().length === 0) {
const status = await fn(); emit("no-media", { msg: "no media received yet" });
if (status.ok) {
clearTimeout(retryTimer);
startPlayer();
hideOverlay();
} else {
showOverlay(status.message);
scheduleRetry();
}
} else {
clearTimeout(retryTimer);
startPlayer();
hideOverlay();
} }
} catch (err: any) { }, 5000);
showOverlay("Check failed: " + err.message);
scheduleRetry(); controller.stop = async () => {
} clearTimeout(trackTimer);
try {
pc.close();
} catch (e) {}
pc = null;
videoEl.srcObject = null;
emit("stopped", {});
};
return controller;
} }
function scheduleRetry() { async function stop() {
clearTimeout(retryTimer); if (controller.stop) await controller.stop();
const retryInterval: number = parseInt( controller.stopped = true;
videoCardEl?.dataset.retryInterval || "5000",
);
retryTimer = setTimeout(checkAndStart, retryInterval);
} }
checkAndStart(); return { start, stop };
}
(videoEl as HTMLVideoElement).volume = 0; function waitForIceGatheringComplete(pc, timeoutMs = 10000) {
(videoEl as HTMLVideoElement).muted = true; return new Promise((resolve) => {
volumeBtn!.textContent = "🔇"; if (!pc) return resolve();
if (pc.iceGatheringState === "complete") return resolve();
volumeBtn!.addEventListener("click", () => { const onState = () => {
if ( if (pc.iceGatheringState === "complete") {
(videoEl as HTMLVideoElement).muted || pc.removeEventListener("icegatheringstatechange", onState);
(videoEl as HTMLVideoElement).volume === 0 clearTimeout(timer);
) { resolve();
(videoEl as HTMLVideoElement).muted = false; }
(videoEl as HTMLVideoElement).volume = 1.0; };
volumeBtn!.textContent = "🔊"; pc.addEventListener("icegatheringstatechange", onState);
} else { const timer = setTimeout(() => {
(videoEl as HTMLVideoElement).muted = true; pc.removeEventListener("icegatheringstatechange", onState);
volumeBtn!.textContent = "🔇"; resolve();
} }, timeoutMs);
}); });
}
fullscreenBtn!.addEventListener("click", async () => { const showOverlay = (msg) => {
const videoCard = document.querySelector(".video-card"); overlayEl.textContent = msg;
if (!document.fullscreenElement) { overlayEl.classList.add("show");
await videoCard!.requestFullscreen(); };
} else { const hideOverlay = () => overlayEl.classList.remove("show");
await document.exitFullscreen();
} const player = createWhepPlayer(streamUrl, videoEl, {
}); iceServers: iceServers,
onEvent: (type, payload) => {
console.log("[whep] event");
console.log("[whep] Type", type);
console.log("[whep] payload", payload);
if (type === "status") showOverlay(payload.msg);
if (type === "playing") hideOverlay();
if (type === "error") showOverlay(payload.msg || payload);
if (type === "disconnected") showOverlay(payload.msg);
if (type === "no-media") showOverlay("Stream not started");
},
});
await player.start();
videoEl.volume = 0;
videoEl.muted = true;
volumeBtn.textContent = "🔇";
volumeBtn.addEventListener("click", () => {
if (videoEl.muted || videoEl.volume === 0) {
videoEl.muted = false;
videoEl.volume = 1.0;
volumeBtn.textContent = "🔊";
} else {
videoEl.muted = true;
volumeBtn.textContent = "🔇";
}
});
fullscreenBtn.addEventListener("click", async () => {
const videoCard = document.querySelector(".video-card");
if (!document.fullscreenElement) {
await videoCard.requestFullscreen();
} else {
await document.exitFullscreen();
}
}); });
</script> </script>
-4
View File
@@ -1,6 +1,3 @@
import { WebRTCPlayer } from "@eyevinn/webrtc-player";
declare global { declare global {
interface Window { interface Window {
schema: any; schema: any;
@@ -8,7 +5,6 @@ declare global {
upload: any; upload: any;
myModal_open: any; myModal_open: any;
myModal_close: any; myModal_close: any;
WebRTCPlayer: typeof WebRTCPlayer
} }
} }