Skip to content

Instantly share code, notes, and snippets.

@birme
Created June 24, 2022 10:59
Show Gist options
  • Save birme/8005156ba4b32fb22670af289133eb29 to your computer and use it in GitHub Desktop.
Save birme/8005156ba4b32fb22670af289133eb29 to your computer and use it in GitHub Desktop.
WHPP example
<!DOCTYPE html>
<html>
<head>
<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/@exampledev/new.css@1.1.2/new.min.css">
</head>
<body>
<video autoplay muted playsinline controls></video>
<script type="text/javascript">
const url = "https://<whpp-url>";
window.addEventListener("DOMContentLoaded", async () => {
let waitingForCandidates = true;
const peer = new RTCPeerConnection({
iceServers: [{ urls: "stun:stun.l.google.com:19302" }]
});
peer.onicegatheringstatechange = async () => {
if (peer.iceGatheringState === "complete") {
await iceGatheringComplete();
}
};
const video = document.querySelector("video");
peer.ontrack = (ev) => {
if (ev.streams && ev.streams[0]) {
video.srcObject = ev.streams[0];
}
};
const response = await fetch(url, {
method: "POST",
headers: { "Content-Type": "application/whpp+json" },
body: JSON.stringify({})
});
const whppOffer = await response.json();
const viewerResourceUrl = response.headers.get("location");
await peer.setRemoteDescription({ type: "offer", sdp: whppOffer.offer });
const answer = peer.createAnswer();
peer.setLocalDescription(answer);
async function iceGatheringComplete() {
waitingForCandidates = false;
clearTimeout(iceGatheringTimeout);
const response = await fetch(viewerResourceUrl, {
method: "PUT",
headers: { "Content-Type": "application/whpp+json" },
body: JSON.stringify({ answer: peer.localDescription.sdp })
});
if (!response.ok) {
console.error(response.statusText);
}
}
const iceGatheringTimeout = setTimeout(async () => {
await iceGatheringComplete();
}, 5000);
});
</script>
</body>
</html>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment