Rewrite WebRTC HTML pages

This commit is contained in:
Alexey Khit
2023-03-08 17:35:28 +03:00
parent e17645ac02
commit f9fe22569c
2 changed files with 92 additions and 121 deletions
+39 -37
View File
@@ -5,61 +5,63 @@
<title>go2rtc - WebRTC</title>
<style>
body {
background-color: black;
margin: 0;
padding: 0;
}
html, body {
html, body, video {
height: 100%;
width: 100%;
}
#video {
/* video "container" size */
width: 100%;
height: 100%;
background: black;
}
</style>
</head>
<body>
<!-- muted is important for autoplay -->
<video id="video" autoplay controls playsinline muted></video>
<script>
// support api_path
const baseUrl = location.origin + location.pathname.substr(
0, location.pathname.lastIndexOf("/")
);
function PeerConnection(userMedia) {
return new Promise((resolve, reject) => {
const pc = new RTCPeerConnection({
iceServers: [{urls: 'stun:stun.l.google.com:19302'}]
})
const pc = new RTCPeerConnection({
iceServers: [
{urls: 'stun:stun.l.google.com:19302'},
]
});
pc.addEventListener('icegatheringstatechange', () => {
if (pc.iceGatheringState === 'complete') resolve(pc)
})
pc.addEventListener('icegatheringstatechange', async () => {
if (pc.iceGatheringState !== 'complete') return;
document.getElementById('video').srcObject = new MediaStream([
pc.addTransceiver('video', {direction: 'recvonly'}).receiver.track,
pc.addTransceiver('audio', {direction: 'recvonly'}).receiver.track
])
let r = await fetch(`${baseUrl}/api/webrtc${location.search}`, {
method: 'POST', body: pc.localDescription.sdp,
});
await pc.setRemoteDescription({
type: 'answer', sdp: await r.text()
});
});
pc.addEventListener('track', ev => {
let video = document.getElementById('video');
if (video.srcObject === null) {
video.srcObject = ev.streams[0];
if (userMedia) {
userMedia.getTracks().forEach(track => {
pc.addTransceiver(track, {direction: 'sendonly'})
})
}
pc.createOffer().then(offer => pc.setLocalDescription(offer))
setTimeout(() => resolve(pc), 3000)
})
}
async function userMedia() {
try {
return await navigator.mediaDevices.getUserMedia({audio: true})
} catch (e) {
return null
}
});
}
pc.addTransceiver('video', {direction: 'recvonly'});
pc.addTransceiver('audio', {direction: 'recvonly'});
async function connect() {
const pc = await PeerConnection(await userMedia())
const url = new URL('api/webrtc' + location.search, location.href)
const r = await fetch(url, {method: 'POST', body: pc.localDescription.sdp})
await pc.setRemoteDescription({type: 'answer', sdp: await r.text()})
}
pc.createOffer().then(offer => {
pc.setLocalDescription(offer);
});
connect()
</script>
</body>
</html>
+53 -84
View File
@@ -5,108 +5,77 @@
<title>go2rtc - WebRTC</title>
<style>
body {
background-color: black;
margin: 0;
padding: 0;
}
html, body {
html, body, video {
height: 100%;
width: 100%;
}
#video {
/* video "container" size */
width: 100%;
height: 100%;
background: black;
}
</style>
</head>
<body>
<video id="video" autoplay controls playsinline muted></video>
<script>
const baseUrl = location.origin + location.pathname.substr(
0, location.pathname.lastIndexOf("/")
);
function init(stream) {
// support api_path
const ws = new WebSocket(`ws${baseUrl.substr(4)}/api/ws${location.search}`);
ws.onopen = () => {
console.debug('ws.onopen');
pc.createOffer().then(offer => {
pc.setLocalDescription(offer).then(() => {
const msg = {type: 'webrtc/offer', value: pc.localDescription.sdp};
ws.send(JSON.stringify(msg));
});
});
}
ws.onmessage = ev => {
const msg = JSON.parse(ev.data);
console.debug('ws.onmessage', msg);
if (msg.type === 'webrtc/candidate') {
pc.addIceCandidate({candidate: msg.value, sdpMid: '0'});
} else if (msg.type === 'webrtc/answer') {
pc.setRemoteDescription({type: 'answer', sdp: msg.value});
}
}
function PeerConnection(userMedia) {
const pc = new RTCPeerConnection({
iceServers: [{urls: 'stun:stun.l.google.com:19302'}]
});
pc.onicecandidate = ev => {
console.debug("pc.onicecandidate", ev.candidate);
})
if (ev.candidate !== null) {
ws.send(JSON.stringify({
type: 'webrtc/candidate', value: ev.candidate.candidate
}));
document.getElementById('video').srcObject = new MediaStream([
pc.addTransceiver('video', {direction: 'recvonly'}).receiver.track,
pc.addTransceiver('audio', {direction: 'recvonly'}).receiver.track
])
if (userMedia) {
userMedia.getTracks().forEach(track => {
pc.addTransceiver(track, {direction: 'sendonly'})
})
}
return pc
}
async function userMedia() {
try {
return await navigator.mediaDevices.getUserMedia({audio: true})
} catch (e) {
return null
}
}
async function connect() {
const pc = PeerConnection(await userMedia())
const url = new URL('api/ws' + location.search, location.href)
const ws = new WebSocket('ws' + url.toString().substring(4))
ws.addEventListener('open', () => {
pc.addEventListener('icecandidate', ev => {
if (!ev.candidate) return
const msg = {type: 'webrtc/candidate', value: ev.candidate.candidate}
ws.send(JSON.stringify(msg))
})
pc.createOffer().then(offer => pc.setLocalDescription(offer)).then(() => {
const msg = {type: 'webrtc/offer', value: pc.localDescription.sdp}
ws.send(JSON.stringify(msg))
})
})
ws.addEventListener('message', ev => {
const msg = JSON.parse(ev.data)
if (msg.type === 'webrtc/candidate') {
pc.addIceCandidate({candidate: msg.value, sdpMid: '0'})
} else if (msg.type === 'webrtc/answer') {
pc.setRemoteDescription({type: 'answer', sdp: msg.value})
}
}
pc.ontrack = ev => {
const video = document.getElementById('video');
console.debug('pc.ontrack', video.srcObject !== null);
// when audio track not exist in Chrome
if (ev.streams.length === 0) return;
// when audio track not exist in Firefox
if (ev.streams[0].id[0] === '{') return;
// when stream already init
if (video.srcObject !== null) return;
video.srcObject = ev.streams[0];
}
if (stream) {
stream.getTracks().forEach(track => {
pc.addTransceiver('audio', {direction: 'sendonly'});
const sender = pc.addTrack(track, stream);
// track.stop();
// setTimeout(() => {
// navigator.mediaDevices.getUserMedia({audio: true}).then(stream => {
// stream.getTracks().forEach(track => {
// sender.replaceTrack(track);
// });
// });
// }, 10000);
});
}
// Safari don't support "offerToReceiveVideo"
// so need to create transeivers manually
pc.addTransceiver('video', {direction: 'recvonly'});
pc.addTransceiver('audio', {direction: 'recvonly'});
})
}
if (navigator.mediaDevices) {
navigator.mediaDevices.getUserMedia({audio: true}).then(init).catch(() => init());
} else {
init();
}
connect()
</script>
</body>
</html>