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> <title>go2rtc - WebRTC</title>
<style> <style>
body { body {
background-color: black;
margin: 0; margin: 0;
padding: 0; padding: 0;
} }
html, body { html, body, video {
height: 100%; height: 100%;
width: 100%; width: 100%;
} }
#video {
/* video "container" size */
width: 100%;
height: 100%;
background: black;
}
</style> </style>
</head> </head>
<body> <body>
<!-- muted is important for autoplay -->
<video id="video" autoplay controls playsinline muted></video> <video id="video" autoplay controls playsinline muted></video>
<script> <script>
// support api_path function PeerConnection(userMedia) {
const baseUrl = location.origin + location.pathname.substr( return new Promise((resolve, reject) => {
0, location.pathname.lastIndexOf("/") const pc = new RTCPeerConnection({
); iceServers: [{urls: 'stun:stun.l.google.com:19302'}]
})
const pc = new RTCPeerConnection({ pc.addEventListener('icegatheringstatechange', () => {
iceServers: [ if (pc.iceGatheringState === 'complete') resolve(pc)
{urls: 'stun:stun.l.google.com:19302'}, })
]
});
pc.addEventListener('icegatheringstatechange', async () => { document.getElementById('video').srcObject = new MediaStream([
if (pc.iceGatheringState !== 'complete') return; pc.addTransceiver('video', {direction: 'recvonly'}).receiver.track,
pc.addTransceiver('audio', {direction: 'recvonly'}).receiver.track
])
let r = await fetch(`${baseUrl}/api/webrtc${location.search}`, { if (userMedia) {
method: 'POST', body: pc.localDescription.sdp, userMedia.getTracks().forEach(track => {
}); pc.addTransceiver(track, {direction: 'sendonly'})
await pc.setRemoteDescription({ })
type: 'answer', sdp: await r.text() }
});
}); pc.createOffer().then(offer => pc.setLocalDescription(offer))
pc.addEventListener('track', ev => {
let video = document.getElementById('video'); setTimeout(() => resolve(pc), 3000)
if (video.srcObject === null) { })
video.srcObject = ev.streams[0]; }
async function userMedia() {
try {
return await navigator.mediaDevices.getUserMedia({audio: true})
} catch (e) {
return null
} }
}); }
pc.addTransceiver('video', {direction: 'recvonly'}); async function connect() {
pc.addTransceiver('audio', {direction: 'recvonly'}); 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 => { connect()
pc.setLocalDescription(offer);
});
</script> </script>
</body> </body>
</html> </html>
+53 -84
View File
@@ -5,108 +5,77 @@
<title>go2rtc - WebRTC</title> <title>go2rtc - WebRTC</title>
<style> <style>
body { body {
background-color: black;
margin: 0; margin: 0;
padding: 0; padding: 0;
} }
html, body { html, body, video {
height: 100%; height: 100%;
width: 100%; width: 100%;
} }
#video {
/* video "container" size */
width: 100%;
height: 100%;
background: black;
}
</style> </style>
</head> </head>
<body> <body>
<video id="video" autoplay controls playsinline muted></video> <video id="video" autoplay controls playsinline muted></video>
<script> <script>
const baseUrl = location.origin + location.pathname.substr( function PeerConnection(userMedia) {
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});
}
}
const pc = new RTCPeerConnection({ const pc = new RTCPeerConnection({
iceServers: [{urls: 'stun:stun.l.google.com:19302'}] iceServers: [{urls: 'stun:stun.l.google.com:19302'}]
}); })
pc.onicecandidate = ev => {
console.debug("pc.onicecandidate", ev.candidate);
if (ev.candidate !== null) { document.getElementById('video').srcObject = new MediaStream([
ws.send(JSON.stringify({ pc.addTransceiver('video', {direction: 'recvonly'}).receiver.track,
type: 'webrtc/candidate', value: ev.candidate.candidate 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) { connect()
navigator.mediaDevices.getUserMedia({audio: true}).then(init).catch(() => init());
} else {
init();
}
</script> </script>
</body> </body>
</html> </html>