New WebRTC Component Changes
This commit is contained in:
@@ -4,6 +4,7 @@ import { cn } from "../utils/cn";
|
||||
|
||||
interface Props extends HTMLAttributes<"div"> {
|
||||
streamUrl: string;
|
||||
iceServers?: any[];
|
||||
poster?: string;
|
||||
checkStreamFn?: string;
|
||||
retryInterval?: number;
|
||||
@@ -11,6 +12,7 @@ interface Props extends HTMLAttributes<"div"> {
|
||||
|
||||
const {
|
||||
streamUrl,
|
||||
iceServers = [],
|
||||
poster,
|
||||
class: className,
|
||||
checkStreamFn,
|
||||
@@ -124,122 +126,193 @@ const {
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<script>
|
||||
document.addEventListener("DOMContentLoaded", () => {
|
||||
const videoCardEl = document.getElementById("video-card");
|
||||
const videoEl = document.getElementById("live-video");
|
||||
const overlayEl = document.getElementById("overlay");
|
||||
const volumeBtn = document.getElementById("volume-btn");
|
||||
const fullscreenBtn = document.getElementById("fullscreen-btn");
|
||||
<script type="module" is:inline define:vars={{ streamUrl, iceServers }}>
|
||||
const videoEl = document.getElementById("live-video");
|
||||
const overlayEl = document.getElementById("overlay");
|
||||
const volumeBtn = document.getElementById("volume-btn");
|
||||
const fullscreenBtn = document.getElementById("fullscreen-btn");
|
||||
|
||||
let player: any;
|
||||
let retryTimer: any;
|
||||
let streamUrl = videoEl?.dataset.stream;
|
||||
function createWhepPlayer(whepUrl, videoEl, opts = {}) {
|
||||
const { iceServers = [], onEvent } = opts;
|
||||
let pc = null;
|
||||
let controller = { stopped: false };
|
||||
|
||||
const showOverlay = (msg: string) => {
|
||||
overlayEl!.textContent = msg;
|
||||
overlayEl!.classList.add("show");
|
||||
};
|
||||
const hideOverlay = () => overlayEl!.classList.remove("show");
|
||||
function emit(type, payload) {
|
||||
if (typeof onEvent === "function") onEvent(type, payload);
|
||||
}
|
||||
|
||||
showOverlay("Connecting to live stream…");
|
||||
async function start() {
|
||||
controller.stopped = false;
|
||||
emit("status", { msg: "starting" });
|
||||
|
||||
async function startPlayer() {
|
||||
try {
|
||||
if (videoEl)
|
||||
player = new window.WebRTCPlayer({
|
||||
video: videoEl as HTMLVideoElement,
|
||||
type: "whep",
|
||||
statsTypeFilter: "^candidate-*|^inbound-rtp",
|
||||
if (pc) {
|
||||
try {
|
||||
pc.close();
|
||||
} catch (e) {}
|
||||
pc = null;
|
||||
}
|
||||
|
||||
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", () => {
|
||||
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);
|
||||
throw new Error("WHEP POST failed: " + res.status);
|
||||
}
|
||||
}
|
||||
|
||||
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 {
|
||||
const checkStreamFn: any =
|
||||
videoCardEl?.dataset.checkStreamFn || "";
|
||||
videoEl.muted = true;
|
||||
await videoEl.play().catch(() => {});
|
||||
emit("playing", { msg: "playing" });
|
||||
} catch (err) {
|
||||
emit("error", { msg: "play failed", err });
|
||||
}
|
||||
|
||||
if (checkStreamFn) {
|
||||
const fn: any = window[checkStreamFn];
|
||||
const status = await fn();
|
||||
if (status.ok) {
|
||||
clearTimeout(retryTimer);
|
||||
startPlayer();
|
||||
hideOverlay();
|
||||
} else {
|
||||
showOverlay(status.message);
|
||||
scheduleRetry();
|
||||
}
|
||||
} else {
|
||||
clearTimeout(retryTimer);
|
||||
startPlayer();
|
||||
hideOverlay();
|
||||
const trackTimer = setTimeout(() => {
|
||||
if (remoteStream.getVideoTracks().length === 0) {
|
||||
emit("no-media", { msg: "no media received yet" });
|
||||
}
|
||||
} catch (err: any) {
|
||||
showOverlay("Check failed: " + err.message);
|
||||
scheduleRetry();
|
||||
}
|
||||
}, 5000);
|
||||
|
||||
controller.stop = async () => {
|
||||
clearTimeout(trackTimer);
|
||||
try {
|
||||
pc.close();
|
||||
} catch (e) {}
|
||||
pc = null;
|
||||
videoEl.srcObject = null;
|
||||
emit("stopped", {});
|
||||
};
|
||||
|
||||
return controller;
|
||||
}
|
||||
|
||||
function scheduleRetry() {
|
||||
clearTimeout(retryTimer);
|
||||
const retryInterval: number = parseInt(
|
||||
videoCardEl?.dataset.retryInterval || "5000",
|
||||
);
|
||||
retryTimer = setTimeout(checkAndStart, retryInterval);
|
||||
async function stop() {
|
||||
if (controller.stop) await controller.stop();
|
||||
controller.stopped = true;
|
||||
}
|
||||
|
||||
checkAndStart();
|
||||
return { start, stop };
|
||||
}
|
||||
|
||||
(videoEl as HTMLVideoElement).volume = 0;
|
||||
(videoEl as HTMLVideoElement).muted = true;
|
||||
volumeBtn!.textContent = "🔇";
|
||||
|
||||
volumeBtn!.addEventListener("click", () => {
|
||||
if (
|
||||
(videoEl as HTMLVideoElement).muted ||
|
||||
(videoEl as HTMLVideoElement).volume === 0
|
||||
) {
|
||||
(videoEl as HTMLVideoElement).muted = false;
|
||||
(videoEl as HTMLVideoElement).volume = 1.0;
|
||||
volumeBtn!.textContent = "🔊";
|
||||
} else {
|
||||
(videoEl as HTMLVideoElement).muted = true;
|
||||
volumeBtn!.textContent = "🔇";
|
||||
}
|
||||
function waitForIceGatheringComplete(pc, timeoutMs = 10000) {
|
||||
return new Promise((resolve) => {
|
||||
if (!pc) return resolve();
|
||||
if (pc.iceGatheringState === "complete") return resolve();
|
||||
const onState = () => {
|
||||
if (pc.iceGatheringState === "complete") {
|
||||
pc.removeEventListener("icegatheringstatechange", onState);
|
||||
clearTimeout(timer);
|
||||
resolve();
|
||||
}
|
||||
};
|
||||
pc.addEventListener("icegatheringstatechange", onState);
|
||||
const timer = setTimeout(() => {
|
||||
pc.removeEventListener("icegatheringstatechange", onState);
|
||||
resolve();
|
||||
}, timeoutMs);
|
||||
});
|
||||
}
|
||||
|
||||
fullscreenBtn!.addEventListener("click", async () => {
|
||||
const videoCard = document.querySelector(".video-card");
|
||||
if (!document.fullscreenElement) {
|
||||
await videoCard!.requestFullscreen();
|
||||
} else {
|
||||
await document.exitFullscreen();
|
||||
}
|
||||
});
|
||||
const showOverlay = (msg) => {
|
||||
overlayEl.textContent = msg;
|
||||
overlayEl.classList.add("show");
|
||||
};
|
||||
const hideOverlay = () => overlayEl.classList.remove("show");
|
||||
|
||||
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>
|
||||
|
||||
Reference in New Issue
Block a user