apply prettier to the entire repository (#5799)

This commit is contained in:
Alessandro Ros
2026-05-26 11:35:14 +02:00
committed by GitHub
parent e63dd7132a
commit 903627ffed
16 changed files with 2213 additions and 2078 deletions
+181 -182
View File
@@ -1,204 +1,203 @@
<!DOCTYPE html>
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width">
<style>
html, body {
margin: 0;
padding: 0;
height: 100%;
font-family: 'Arial', sans-serif;
}
#video {
position: absolute;
top: 0;
left: 0;
width: 100%;
height: 100%;
background: rgb(30, 30, 30);
}
#message {
position: absolute;
left: 0;
top: 0;
width: 100%;
height: 100%;
display: flex;
align-items: center;
text-align: center;
justify-content: center;
font-size: 16px;
font-weight: bold;
color: white;
pointer-events: none;
padding: 20px;
box-sizing: border-box;
text-shadow: 0 0 5px black;
}
#lang-icon {
display: none;
position: absolute;
top: 20px;
right: 20px;
width: 30px;
height: 30px;
background-image: url("data:image/svg+xml;base64,PHN2ZyB4bWxucz0iaHR0cDovL3d3dy53My5vcmcvMjAwMC9zdmciIHZpZXdCb3g9IjAgMCA1MCA1MCIgZmlsbD0iI2ZmZiIgeG1sbnM6dj0iaHR0cHM6Ly92ZWN0YS5pby9uYW5vIj48cGF0aCBkPSJNMzguNSAzMy45bC0xLjktMS42YzIuNS0yLjkgMy44LTYuMyAzLjgtOS45IDAtMy4xLTEtNi4xLTIuOS04LjhsMi4xLTEuNWMyLjIgMy4xIDMuNCA2LjYgMy40IDEwLjItLjEgNC4zLTEuNiA4LjMtNC41IDExLjZ6TTUuNiAyMy4yaC0zYy0uNSAwLTEgLjUtMSAxLjF2MTAuNWMwIC42LjQgMS4xIDEgMS4xaDNjLjIgMCAuMyAwIC40LjFsMTMuOCA3LjhjLjYuNCAxLjQtLjIgMS40LTFWMTYuM2MwLS44LS44LTEuMy0xLjQtMUw2LjEgMjMuMWMtLjIuMS0uMy4xLS41LjF6bTIxLTE2LjlMMTIuOCAxNGMtLjEuMS0uMy4xLS40LjFoLTNjLS41IDAtMSAuNS0xIDEuMVYyMGwxMi4yLTYuOGExLjM2IDEuMzYgMCAwIDEgMS41IDBjLjUuMy44LjguOCAxLjV2MTcuOWwzLjcgMi4xYy42LjQgMS40LS4yIDEuNC0xVjcuMmMuMS0uOC0uNy0xLjMtMS40LS45em0xNi41IDMwLjJsLTEuOS0xLjZjMy4xLTMuNyA0LjctOCA0LjctMTIuNSAwLTQtMS4zLTcuOC0zLjctMTEuMmwyLjEtMS41YzIuNyAzLjggNC4yIDguMiA0LjIgMTIuNy0uMiA1LjEtMiA5LjktNS40IDE0LjF6TTM1IDMxLjFsLTItMS42YzEuNy0yLjEgMi42LTQuNiAyLjYtNy4yIDAtMi40LS44LTQuNy0yLjItNi43bDItMS41YzEuOCAyLjUgMi43IDUuMyAyLjcgOC4yIDAgMy4yLTEuMSA2LjItMy4xIDguOHoiLz48L3N2Zz4=");
background-size: 80%;
background-position: center;
background-repeat: no-repeat;
cursor: pointer;
}
#lang-list {
display: none;
position: absolute;
top: 100%;
right: 0;
background: rgb(190, 190, 190);
color: black;
}
#lang-icon:hover #lang-list {
display: block;
}
#lang-list div {
border-bottom: 1px solid black;
padding: 5px 15px;
}
</style>
</head>
<body>
<head>
<meta charset="utf-8" />
<meta name="viewport" content="width=device-width" />
<style>
html,
body {
margin: 0;
padding: 0;
height: 100%;
font-family: "Arial", sans-serif;
}
#video {
position: absolute;
top: 0;
left: 0;
width: 100%;
height: 100%;
background: rgb(30, 30, 30);
}
#message {
position: absolute;
left: 0;
top: 0;
width: 100%;
height: 100%;
display: flex;
align-items: center;
text-align: center;
justify-content: center;
font-size: 16px;
font-weight: bold;
color: white;
pointer-events: none;
padding: 20px;
box-sizing: border-box;
text-shadow: 0 0 5px black;
}
#lang-icon {
display: none;
position: absolute;
top: 20px;
right: 20px;
width: 30px;
height: 30px;
background-image: url("data:image/svg+xml;base64,PHN2ZyB4bWxucz0iaHR0cDovL3d3dy53My5vcmcvMjAwMC9zdmciIHZpZXdCb3g9IjAgMCA1MCA1MCIgZmlsbD0iI2ZmZiIgeG1sbnM6dj0iaHR0cHM6Ly92ZWN0YS5pby9uYW5vIj48cGF0aCBkPSJNMzguNSAzMy45bC0xLjktMS42YzIuNS0yLjkgMy44LTYuMyAzLjgtOS45IDAtMy4xLTEtNi4xLTIuOS04LjhsMi4xLTEuNWMyLjIgMy4xIDMuNCA2LjYgMy40IDEwLjItLjEgNC4zLTEuNiA4LjMtNC41IDExLjZ6TTUuNiAyMy4yaC0zYy0uNSAwLTEgLjUtMSAxLjF2MTAuNWMwIC42LjQgMS4xIDEgMS4xaDNjLjIgMCAuMyAwIC40LjFsMTMuOCA3LjhjLjYuNCAxLjQtLjIgMS40LTFWMTYuM2MwLS44LS44LTEuMy0xLjQtMUw2LjEgMjMuMWMtLjIuMS0uMy4xLS41LjF6bTIxLTE2LjlMMTIuOCAxNGMtLjEuMS0uMy4xLS40LjFoLTNjLS41IDAtMSAuNS0xIDEuMVYyMGwxMi4yLTYuOGExLjM2IDEuMzYgMCAwIDEgMS41IDBjLjUuMy44LjguOCAxLjV2MTcuOWwzLjcgMi4xYy42LjQgMS40LS4yIDEuNC0xVjcuMmMuMS0uOC0uNy0xLjMtMS40LS45em0xNi41IDMwLjJsLTEuOS0xLjZjMy4xLTMuNyA0LjctOCA0LjctMTIuNSAwLTQtMS4zLTcuOC0zLjctMTEuMmwyLjEtMS41YzIuNyAzLjggNC4yIDguMiA0LjIgMTIuNy0uMiA1LjEtMiA5LjktNS40IDE0LjF6TTM1IDMxLjFsLTItMS42YzEuNy0yLjEgMi42LTQuNiAyLjYtNy4yIDAtMi40LS44LTQuNy0yLjItNi43bDItMS41YzEuOCAyLjUgMi43IDUuMyAyLjcgOC4yIDAgMy4yLTEuMSA2LjItMy4xIDguOHoiLz48L3N2Zz4=");
background-size: 80%;
background-position: center;
background-repeat: no-repeat;
cursor: pointer;
}
#lang-list {
display: none;
position: absolute;
top: 100%;
right: 0;
background: rgb(190, 190, 190);
color: black;
}
#lang-icon:hover #lang-list {
display: block;
}
#lang-list div {
border-bottom: 1px solid black;
padding: 5px 15px;
}
</style>
</head>
<body>
<video id="video"></video>
<div id="message"></div>
<div id="lang-icon"><div id="lang-list"></div></div>
<video id="video"></video>
<div id="message"></div>
<div id="lang-icon"><div id="lang-list"></div></div>
<script defer src="hls.min.js"></script>
<script defer src="hls.min.js"></script>
<script>
const retryPause = 2000;
<script>
const video = document.getElementById("video");
const message = document.getElementById("message");
const langIcon = document.getElementById("lang-icon");
const langList = document.getElementById("lang-list");
const retryPause = 2000;
let defaultControls = false;
const video = document.getElementById('video');
const message = document.getElementById('message');
const langIcon = document.getElementById('lang-icon');
const langList = document.getElementById('lang-list');
const setMessage = (str) => {
if (str !== "") {
video.controls = false;
} else {
video.controls = defaultControls;
}
message.innerText = str;
};
let defaultControls = false;
const isIOS = () =>
/iPad|iPhone|iPod/.test(navigator.platform) ||
(navigator.platform === "MacIntel" && navigator.maxTouchPoints > 1);
const setMessage = (str) => {
if (str !== '') {
video.controls = false;
} else {
video.controls = defaultControls;
}
message.innerText = str;
};
const loadStream = () => {
// Prefer hls.js over native HLS.
// This is because some Android versions support native HLS
// but don't support fMP4s.
// Skip iPad iOS >= 13 and iPhone iOS >= 17,
// which support hls.js but don't support well maxLiveSyncPlaybackRate.
if (Hls.isSupported() && !isIOS()) {
const hls = new Hls({
maxLiveSyncPlaybackRate: 1.5,
});
const isIOS = () => (
/iPad|iPhone|iPod/.test(navigator.platform)
|| (navigator.platform === 'MacIntel' && navigator.maxTouchPoints > 1)
);
hls.on(Hls.Events.ERROR, (evt, data) => {
if (data.fatal) {
hls.destroy();
const loadStream = () => {
// Prefer hls.js over native HLS.
// This is because some Android versions support native HLS
// but don't support fMP4s.
// Skip iPad iOS >= 13 and iPhone iOS >= 17,
// which support hls.js but don't support well maxLiveSyncPlaybackRate.
if (Hls.isSupported() && !isIOS()) {
const hls = new Hls({
maxLiveSyncPlaybackRate: 1.5,
});
langIcon.style.display = "none";
langList.innerHTML = "";
hls.on(Hls.Events.ERROR, (evt, data) => {
if (data.fatal) {
hls.destroy();
if (data.details === "manifestIncompatibleCodecsError") {
setMessage(
"stream makes use of codecs which are not compatible with this browser or operative system",
);
} else if (data.response && data.response.code === 404) {
setMessage("stream not found, retrying in some seconds");
} else {
setMessage(data.error + ", retrying in some seconds");
}
langIcon.style.display = 'none';
langList.innerHTML = '';
setTimeout(() => loadStream(), retryPause);
}
});
if (data.details === 'manifestIncompatibleCodecsError') {
setMessage('stream makes use of codecs which are not compatible with this browser or operative system');
} else if (data.response && data.response.code === 404) {
setMessage('stream not found, retrying in some seconds');
} else {
setMessage(data.error + ', retrying in some seconds');
}
hls.on(Hls.Events.MEDIA_ATTACHED, () => {
hls.loadSource("index.m3u8" + window.location.search);
});
setTimeout(() => loadStream(), retryPause);
}
});
hls.on(Hls.Events.MANIFEST_LOADED, () => {
if (hls.audioTracks.length > 1) {
for (const track of hls.audioTracks) {
const div = document.createElement("DIV");
div.innerText = track.name;
div.addEventListener("click", () => {
hls.audioTrack = track.id;
});
langList.appendChild(div);
}
langIcon.style.display = "block";
}
hls.on(Hls.Events.MEDIA_ATTACHED, () => {
hls.loadSource('index.m3u8' + window.location.search);
});
setMessage("");
video.play();
});
hls.on(Hls.Events.MANIFEST_LOADED, () => {
if (hls.audioTracks.length > 1) {
for (const track of hls.audioTracks) {
const div = document.createElement('DIV');
div.innerText = track.name;
div.addEventListener('click', () => {
hls.audioTrack = track.id;
});
langList.appendChild(div);
}
langIcon.style.display = 'block';
}
// when the video is resumed after a manual or forced pause
// (i.e. when the window is minimized), restore live streaming.
video.onplay = () => {
video.currentTime = hls.liveSyncPosition;
};
setMessage('');
video.play();
});
hls.attachMedia(video);
} else if (video.canPlayType("application/vnd.apple.mpegurl")) {
// since it's not possible to detect timeout errors in iOS,
// wait for the playlist to be available before starting the stream
fetch("index.m3u8" + window.location.search).then(() => {
video.src = "index.m3u8" + window.location.search;
video.play();
});
}
};
// when the video is resumed after a manual or forced pause
// (i.e. when the window is minimized), restore live streaming.
video.onplay = () => {
video.currentTime = hls.liveSyncPosition;
};
const parseBoolString = (str, defaultVal) => {
str = str || "";
hls.attachMedia(video);
if (["1", "yes", "true"].includes(str.toLowerCase())) {
return true;
}
if (["0", "no", "false"].includes(str.toLowerCase())) {
return false;
}
return defaultVal;
};
} else if (video.canPlayType('application/vnd.apple.mpegurl')) {
// since it's not possible to detect timeout errors in iOS,
// wait for the playlist to be available before starting the stream
fetch('index.m3u8' + window.location.search)
.then(() => {
video.src = 'index.m3u8' + window.location.search;
video.play();
});
}
};
const loadAttributesFromQuery = () => {
const params = new URLSearchParams(window.location.search);
video.controls = parseBoolString(params.get("controls"), true);
video.muted = parseBoolString(params.get("muted"), true);
video.autoplay = parseBoolString(params.get("autoplay"), true);
video.playsInline = parseBoolString(params.get("playsinline"), true);
video.disablepictureinpicture = parseBoolString(
params.get("disablepictureinpicture"),
false,
);
defaultControls = video.controls;
};
const parseBoolString = (str, defaultVal) => {
str = (str || '');
if (['1', 'yes', 'true'].includes(str.toLowerCase())) {
return true;
}
if (['0', 'no', 'false'].includes(str.toLowerCase())) {
return false;
}
return defaultVal;
};
const loadAttributesFromQuery = () => {
const params = new URLSearchParams(window.location.search);
video.controls = parseBoolString(params.get('controls'), true);
video.muted = parseBoolString(params.get('muted'), true);
video.autoplay = parseBoolString(params.get('autoplay'), true);
video.playsInline = parseBoolString(params.get('playsinline'), true);
video.disablepictureinpicture = parseBoolString(params.get('disablepictureinpicture'), false);
defaultControls = video.controls;
};
// use load instead of DOMContentLoaded, otherwise, in Firefox,
// the page gets stuck in the "loading" state.
window.addEventListener('load', () => {
loadAttributesFromQuery();
loadStream();
});
</script>
</body>
// use load instead of DOMContentLoaded, otherwise, in Firefox,
// the page gets stuck in the "loading" state.
window.addEventListener("load", () => {
loadAttributesFromQuery();
loadStream();
});
</script>
</body>
</html>
+427 -408
View File
@@ -1,434 +1,453 @@
<!DOCTYPE html>
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width">
<style>
html, body {
margin: 0;
padding: 0;
height: 100%;
font-family: 'Arial', sans-serif;
}
#video {
position: absolute;
top: 0;
left: 0;
width: 100%;
height: 100%;
background: rgb(30, 30, 30);
}
#controls {
display: none;
flex-shrink: 0;
align-items: center;
justify-content: center;
padding: 10px;
flex-direction: column;
min-height: 100%;
width: 100%;
box-sizing: border-box;
background: rgb(30, 30, 30);
color: white;
}
.item {
display: grid;
grid-auto-flow: column;
grid-template-columns: auto 220px;
align-items: center;
gap: 20px;
max-width: 500px;
margin: 10px 0;
}
select, input[type="text"] {
appearance: none;
background: inherit;
color: inherit;
border: 1px solid rgb(200, 200, 200);
border-radius: 3px;
height: 40px;
padding: 0 10px;
}
select option {
color: black;
}
#message {
position: absolute;
left: 0;
top: 0;
width: 100%;
height: 100%;
display: flex;
align-items: center;
text-align: center;
justify-content: center;
font-size: 16px;
font-weight: bold;
color: white;
pointer-events: none;
padding: 20px;
box-sizing: border-box;
text-shadow: 0 0 5px black;
}
#publish-button {
margin-top: 10px;
appearance: none;
background: rgb(200, 200, 200);
color: black;
border-radius: 3px;
height: 50px;
padding: 0 20px;
border: none;
}
</style>
<script defer src="./publisher.js"></script>
</head>
<body>
<video id="video" muted autoplay playsinline></video>
<div id="controls">
<div id="items">
<div class="item">
<label for="video-device">video device</label>
<select id="video-device">
<option value="none">none</option>
</select>
</div>
<div class="item">
<label for="video-codec">video codec</label>
<select id="video-codec">
</select>
</div>
<div class="item">
<label for="video-bitrate">video bitrate (kbps)</label>
<input id="video-bitrate" type="text" value="10000" />
</div>
<div class="item">
<label for="video-framerate">video framerate (ideal)</label>
<input id="video-framerate" type="text" value="30" />
</div>
<div class="item">
<label for="video-width">video width (ideal)</label>
<input id="video-width" type="text" value="1920" />
</div>
<div class="item">
<label for="video-height">video height (ideal)</label>
<input id="video-height" type="text" value="1080" />
</div>
<div class="item">
<label for="audio-device">audio device</label>
<select id="audio-device">
<option value="none">none</option>
</select>
</div>
<div class="item">
<label for="audio-codec">audio codec</label>
<select id="audio-codec">
</select>
</div>
<div class="item">
<label for="audio-bitrate">audio bitrate (kbps)</label>
<input id="audio-bitrate" type="text" value="32" />
</div>
<div class="item">
<label for="audio-voice">optimize for voice</label>
<div>
<input id="audio-voice" type="checkbox" checked>
</div>
</div>
</div>
<div id="submit-line">
<button id="publish-button">publish</button>
</div>
</div>
<div id="message"></div>
<script>
const video = document.getElementById('video');
const controls = document.getElementById('controls');
const message = document.getElementById('message');
const publishButton = document.getElementById('publish-button');
let publisher = null;
const videoForm = {
device: document.getElementById('video-device'),
codec: document.getElementById('video-codec'),
bitrate: document.getElementById('video-bitrate'),
framerate: document.getElementById('video-framerate'),
width: document.getElementById('video-width'),
height: document.getElementById('video-height')
};
const audioForm = {
device: document.getElementById('audio-device'),
codec: document.getElementById('audio-codec'),
bitrate: document.getElementById('audio-bitrate'),
voice: document.getElementById('audio-voice'),
};
const setMessage = (str) => {
message.innerText = str;
};
const onStream = (stream) => {
video.srcObject = stream;
publisher = new MediaMTXWebRTCPublisher({
url: new URL('whip', window.location.href) + window.location.search,
stream,
videoCodec: videoForm.codec.value,
videoBitrate: videoForm.bitrate.value,
audioCodec: audioForm.codec.value,
audioBitrate: audioForm.bitrate.value,
audioVoice: audioForm.voice.checked,
onError: (err) => {
setMessage(err);
},
onConnected: (evt) => {
setMessage('');
},
});
};
const onPublish = () => {
controls.style.display = 'none';
video.style.display = 'block';
setMessage('connecting');
const videoId = videoForm.device.value;
const audioId = audioForm.device.value;
if (videoId !== 'screen') {
let videoOpts = false;
if (videoId !== 'none') {
videoOpts = {
deviceId: videoId,
width: { ideal: videoForm.width.value },
height: { ideal: videoForm.height.value },
frameRate: { ideal: videoForm.framerate.value },
};
}
let audioOpts = false;
if (audioId !== 'none') {
audioOpts = {
deviceId: audioId,
};
const voice = audioForm.voice.checked;
if (!voice) {
audioOpts.autoGainControl = false;
audioOpts.echoCancellation = false;
audioOpts.noiseSuppression = false;
<head>
<meta charset="utf-8" />
<meta name="viewport" content="width=device-width" />
<style>
html,
body {
margin: 0;
padding: 0;
height: 100%;
font-family: "Arial", sans-serif;
}
}
#video {
position: absolute;
top: 0;
left: 0;
width: 100%;
height: 100%;
background: rgb(30, 30, 30);
}
#controls {
display: none;
flex-shrink: 0;
align-items: center;
justify-content: center;
padding: 10px;
flex-direction: column;
min-height: 100%;
width: 100%;
box-sizing: border-box;
background: rgb(30, 30, 30);
color: white;
}
.item {
display: grid;
grid-auto-flow: column;
grid-template-columns: auto 220px;
align-items: center;
gap: 20px;
max-width: 500px;
margin: 10px 0;
}
select,
input[type="text"] {
appearance: none;
background: inherit;
color: inherit;
border: 1px solid rgb(200, 200, 200);
border-radius: 3px;
height: 40px;
padding: 0 10px;
}
select option {
color: black;
}
#message {
position: absolute;
left: 0;
top: 0;
width: 100%;
height: 100%;
display: flex;
align-items: center;
text-align: center;
justify-content: center;
font-size: 16px;
font-weight: bold;
color: white;
pointer-events: none;
padding: 20px;
box-sizing: border-box;
text-shadow: 0 0 5px black;
}
#publish-button {
margin-top: 10px;
appearance: none;
background: rgb(200, 200, 200);
color: black;
border-radius: 3px;
height: 50px;
padding: 0 20px;
border: none;
}
</style>
<script defer src="./publisher.js"></script>
</head>
<body>
<video id="video" muted autoplay playsinline></video>
navigator.mediaDevices.getUserMedia({
video: videoOpts,
audio: audioOpts,
})
.then((stream) => onStream(stream))
.catch((err) => {
setMessage(err.toString());
});
} else {
navigator.mediaDevices.getDisplayMedia({
video: {
width: { ideal: videoForm.width.value },
height: { ideal: videoForm.height.value },
frameRate: { ideal: videoForm.framerate.value },
cursor: 'always',
},
audio: true,
})
.then((stream) => onStream(stream))
.catch((err) => {
setMessage(err.toString());
});
}
};
<div id="controls">
<div id="items">
<div class="item">
<label for="video-device">video device</label>
<select id="video-device">
<option value="none">none</option>
</select>
</div>
const selectHasOption = (select, option) => {
for (const opt of select.querySelectorAll('option')) {
if (opt.value === option) {
return true;
}
}
return false;
};
<div class="item">
<label for="video-codec">video codec</label>
<select id="video-codec"></select>
</div>
const populateDevices = () => {
return navigator.mediaDevices.enumerateDevices()
.then((devices) => {
for (const device of devices) {
if (device.kind === 'videoinput' || device.kind === 'audioinput') {
const select = (device.kind === 'videoinput') ? videoForm.device : audioForm.device;
<div class="item">
<label for="video-bitrate">video bitrate (kbps)</label>
<input id="video-bitrate" type="text" value="10000" />
</div>
if (!selectHasOption(select, device.deviceId)) {
const opt = document.createElement('option');
opt.value = device.deviceId;
opt.text = device.label;
select.appendChild(opt);
<div class="item">
<label for="video-framerate">video framerate (ideal)</label>
<input id="video-framerate" type="text" value="30" />
</div>
<div class="item">
<label for="video-width">video width (ideal)</label>
<input id="video-width" type="text" value="1920" />
</div>
<div class="item">
<label for="video-height">video height (ideal)</label>
<input id="video-height" type="text" value="1080" />
</div>
<div class="item">
<label for="audio-device">audio device</label>
<select id="audio-device">
<option value="none">none</option>
</select>
</div>
<div class="item">
<label for="audio-codec">audio codec</label>
<select id="audio-codec"></select>
</div>
<div class="item">
<label for="audio-bitrate">audio bitrate (kbps)</label>
<input id="audio-bitrate" type="text" value="32" />
</div>
<div class="item">
<label for="audio-voice">optimize for voice</label>
<div>
<input id="audio-voice" type="checkbox" checked />
</div>
</div>
</div>
<div id="submit-line">
<button id="publish-button">publish</button>
</div>
</div>
<div id="message"></div>
<script>
const video = document.getElementById("video");
const controls = document.getElementById("controls");
const message = document.getElementById("message");
const publishButton = document.getElementById("publish-button");
let publisher = null;
const videoForm = {
device: document.getElementById("video-device"),
codec: document.getElementById("video-codec"),
bitrate: document.getElementById("video-bitrate"),
framerate: document.getElementById("video-framerate"),
width: document.getElementById("video-width"),
height: document.getElementById("video-height"),
};
const audioForm = {
device: document.getElementById("audio-device"),
codec: document.getElementById("audio-codec"),
bitrate: document.getElementById("audio-bitrate"),
voice: document.getElementById("audio-voice"),
};
const setMessage = (str) => {
message.innerText = str;
};
const onStream = (stream) => {
video.srcObject = stream;
publisher = new MediaMTXWebRTCPublisher({
url: new URL("whip", window.location.href) + window.location.search,
stream,
videoCodec: videoForm.codec.value,
videoBitrate: videoForm.bitrate.value,
audioCodec: audioForm.codec.value,
audioBitrate: audioForm.bitrate.value,
audioVoice: audioForm.voice.checked,
onError: (err) => {
setMessage(err);
},
onConnected: (evt) => {
setMessage("");
},
});
};
const onPublish = () => {
controls.style.display = "none";
video.style.display = "block";
setMessage("connecting");
const videoId = videoForm.device.value;
const audioId = audioForm.device.value;
if (videoId !== "screen") {
let videoOpts = false;
if (videoId !== "none") {
videoOpts = {
deviceId: videoId,
width: { ideal: videoForm.width.value },
height: { ideal: videoForm.height.value },
frameRate: { ideal: videoForm.framerate.value },
};
}
let audioOpts = false;
if (audioId !== "none") {
audioOpts = {
deviceId: audioId,
};
const voice = audioForm.voice.checked;
if (!voice) {
audioOpts.autoGainControl = false;
audioOpts.echoCancellation = false;
audioOpts.noiseSuppression = false;
}
}
navigator.mediaDevices
.getUserMedia({
video: videoOpts,
audio: audioOpts,
})
.then((stream) => onStream(stream))
.catch((err) => {
setMessage(err.toString());
});
} else {
navigator.mediaDevices
.getDisplayMedia({
video: {
width: { ideal: videoForm.width.value },
height: { ideal: videoForm.height.value },
frameRate: { ideal: videoForm.framerate.value },
cursor: "always",
},
audio: true,
})
.then((stream) => onStream(stream))
.catch((err) => {
setMessage(err.toString());
});
}
};
const selectHasOption = (select, option) => {
for (const opt of select.querySelectorAll("option")) {
if (opt.value === option) {
return true;
}
}
}
return false;
};
if (navigator.mediaDevices.getDisplayMedia !== undefined) {
const opt = document.createElement('option');
opt.value = 'screen';
opt.text = 'screen';
videoForm.device.appendChild(opt);
}
const populateDevices = () => {
return navigator.mediaDevices.enumerateDevices().then((devices) => {
for (const device of devices) {
if (device.kind === "videoinput" || device.kind === "audioinput") {
const select =
device.kind === "videoinput"
? videoForm.device
: audioForm.device;
// set first available device as default device
if (videoForm.device.children.length !== 0) {
videoForm.device.value = videoForm.device.children[1].value;
}
if (!selectHasOption(select, device.deviceId)) {
const opt = document.createElement("option");
opt.value = device.deviceId;
opt.text = device.label;
select.appendChild(opt);
}
}
}
// set first available device as default device
if (audioForm.device.children.length !== 0) {
audioForm.device.value = audioForm.device.children[1].value;
}
});
};
if (navigator.mediaDevices.getDisplayMedia !== undefined) {
const opt = document.createElement("option");
opt.value = "screen";
opt.text = "screen";
videoForm.device.appendChild(opt);
}
const populateCodecs = () => {
const tempPC = new RTCPeerConnection({});
tempPC.addTransceiver('video', { direction: 'sendonly' });
tempPC.addTransceiver('audio', { direction: 'sendonly' });
// set first available device as default device
if (videoForm.device.children.length !== 0) {
videoForm.device.value = videoForm.device.children[1].value;
}
return tempPC.createOffer()
.then((desc) => {
const sdp = desc.sdp.toLowerCase();
for (const codec of ['av1/90000', 'vp9/90000', 'vp8/90000', 'h264/90000', 'h265/90000']) {
if (sdp.includes(codec)) {
const opt = document.createElement('option');
opt.value = codec;
opt.text = codec.split('/')[0].toUpperCase();
videoForm.codec.appendChild(opt);
}
}
for (const codec of ['opus/48000', 'g722/8000', 'pcmu/8000', 'pcma/8000']) {
if (sdp.includes(codec)) {
const opt = document.createElement('option');
opt.value = codec;
opt.text = codec.split('/')[0].toUpperCase();
audioForm.codec.appendChild(opt);
}
}
tempPC.close();
});
};
const populateOptions = () => {
setMessage('loading devices');
navigator.mediaDevices.getUserMedia({ video: true, audio: true })
.then((tempStream) => {
return Promise.all([
populateDevices(),
populateCodecs(),
])
.then(() => {
// free the webcam to prevent 'NotReadableError' on Android
tempStream.getTracks()
.forEach((track) => track.stop());
setMessage('');
loadValuesFromQuery();
setupEventListeners();
video.style.display = 'none';
controls.style.display = 'flex';
// set first available device as default device
if (audioForm.device.children.length !== 0) {
audioForm.device.value = audioForm.device.children[1].value;
}
});
})
.catch((err) => {
setMessage(err.toString());
});
};
};
const setupEventListeners = () => {
const url = new URL(window.location.href);
const inputs = [...Object.values(videoForm), ...Object.values(audioForm)]
const populateCodecs = () => {
const tempPC = new RTCPeerConnection({});
tempPC.addTransceiver("video", { direction: "sendonly" });
tempPC.addTransceiver("audio", { direction: "sendonly" });
for (const input of inputs) {
if (input instanceof HTMLInputElement && input.type === 'text') {
input.addEventListener('input', () => {
url.searchParams.set(input.id, input.value);
window.history.replaceState(null, null, url);
})
}
return tempPC.createOffer().then((desc) => {
const sdp = desc.sdp.toLowerCase();
if (input instanceof HTMLInputElement && input.type === 'checkbox') {
input.addEventListener('input', () => {
url.searchParams.set(input.id, input.checked);
window.history.replaceState(null, null, url);
})
}
for (const codec of [
"av1/90000",
"vp9/90000",
"vp8/90000",
"h264/90000",
"h265/90000",
]) {
if (sdp.includes(codec)) {
const opt = document.createElement("option");
opt.value = codec;
opt.text = codec.split("/")[0].toUpperCase();
videoForm.codec.appendChild(opt);
}
}
if (input instanceof HTMLSelectElement) {
input.addEventListener('input', () => {
url.searchParams.set(input.id, input.value);
window.history.replaceState(null, null, url);
})
}
}
};
for (const codec of [
"opus/48000",
"g722/8000",
"pcmu/8000",
"pcma/8000",
]) {
if (sdp.includes(codec)) {
const opt = document.createElement("option");
opt.value = codec;
opt.text = codec.split("/")[0].toUpperCase();
audioForm.codec.appendChild(opt);
}
}
const loadValuesFromQuery = () => {
const params = new URLSearchParams(window.location.search);
const inputs = [...Object.values(videoForm), ...Object.values(audioForm)]
tempPC.close();
});
};
for (const input of inputs) {
const value = params.get(input.id);
if (value) {
if (input instanceof HTMLInputElement && input.type === 'text') {
input.value = value;
} else if (input instanceof HTMLInputElement && input.type === 'checkbox') {
input.checked = value === 'true';
} else if (input instanceof HTMLSelectElement) {
input.value = value;
}
}
}
};
const populateOptions = () => {
setMessage("loading devices");
window.addEventListener('load', () => {
if (navigator.mediaDevices === undefined) {
setMessage(`can't access webcams or microphones. Make sure that WebRTC encryption is enabled.`);
return;
}
navigator.mediaDevices
.getUserMedia({ video: true, audio: true })
.then((tempStream) => {
return Promise.all([populateDevices(), populateCodecs()]).then(
() => {
// free the webcam to prevent 'NotReadableError' on Android
tempStream.getTracks().forEach((track) => track.stop());
publishButton.addEventListener('click', onPublish);
populateOptions();
});
setMessage("");
window.addEventListener('beforeunload', () => {
if (publisher !== null) {
publisher.close();
}
});
loadValuesFromQuery();
setupEventListeners();
</script>
video.style.display = "none";
controls.style.display = "flex";
},
);
})
.catch((err) => {
setMessage(err.toString());
});
};
</body>
const setupEventListeners = () => {
const url = new URL(window.location.href);
const inputs = [
...Object.values(videoForm),
...Object.values(audioForm),
];
for (const input of inputs) {
if (input instanceof HTMLInputElement && input.type === "text") {
input.addEventListener("input", () => {
url.searchParams.set(input.id, input.value);
window.history.replaceState(null, null, url);
});
}
if (input instanceof HTMLInputElement && input.type === "checkbox") {
input.addEventListener("input", () => {
url.searchParams.set(input.id, input.checked);
window.history.replaceState(null, null, url);
});
}
if (input instanceof HTMLSelectElement) {
input.addEventListener("input", () => {
url.searchParams.set(input.id, input.value);
window.history.replaceState(null, null, url);
});
}
}
};
const loadValuesFromQuery = () => {
const params = new URLSearchParams(window.location.search);
const inputs = [
...Object.values(videoForm),
...Object.values(audioForm),
];
for (const input of inputs) {
const value = params.get(input.id);
if (value) {
if (input instanceof HTMLInputElement && input.type === "text") {
input.value = value;
} else if (
input instanceof HTMLInputElement &&
input.type === "checkbox"
) {
input.checked = value === "true";
} else if (input instanceof HTMLSelectElement) {
input.value = value;
}
}
}
};
window.addEventListener("load", () => {
if (navigator.mediaDevices === undefined) {
setMessage(
`can't access webcams or microphones. Make sure that WebRTC encryption is enabled.`,
);
return;
}
publishButton.addEventListener("click", onPublish);
populateOptions();
});
window.addEventListener("beforeunload", () => {
if (publisher !== null) {
publisher.close();
}
});
</script>
</body>
</html>
+167 -128
View File
@@ -1,4 +1,4 @@
'use strict';
"use strict";
/**
* @callback OnError
@@ -44,7 +44,7 @@ class MediaMTXWebRTCPublisher {
constructor(conf) {
this.#retryPause = 2000;
this.#conf = conf;
this.#state = 'running';
this.#state = "running";
this.#restartTimeout = null;
this.#pc = null;
this.#offerData = null;
@@ -57,7 +57,7 @@ class MediaMTXWebRTCPublisher {
* Close the publisher and all its resources.
*/
close = () => {
this.#state = 'closed';
this.#state = "closed";
if (this.#pc !== null) {
this.#pc.close();
@@ -73,36 +73,40 @@ class MediaMTXWebRTCPublisher {
}
static #linkToIceServers(links) {
return (links !== null) ? links.split(', ').map((link) => {
const m = link.match(/^<(.+?)>; rel="ice-server"(; username="(.*?)"; credential="(.*?)"; credential-type="password")?/i);
const ret = {
urls: [m[1]],
};
return links !== null
? links.split(", ").map((link) => {
const m = link.match(
/^<(.+?)>; rel="ice-server"(; username="(.*?)"; credential="(.*?)"; credential-type="password")?/i,
);
const ret = {
urls: [m[1]],
};
if (m[3] !== undefined) {
ret.username = this.#unquoteCredential(m[3]);
ret.credential = this.#unquoteCredential(m[4]);
ret.credentialType = 'password';
}
if (m[3] !== undefined) {
ret.username = this.#unquoteCredential(m[3]);
ret.credential = this.#unquoteCredential(m[4]);
ret.credentialType = "password";
}
return ret;
}) : [];
return ret;
})
: [];
}
static #parseOffer(offer) {
const ret = {
iceUfrag: '',
icePwd: '',
iceUfrag: "",
icePwd: "",
medias: [],
};
for (const line of offer.split('\r\n')) {
if (line.startsWith('m=')) {
ret.medias.push(line.slice('m='.length));
} else if (ret.iceUfrag === '' && line.startsWith('a=ice-ufrag:')) {
ret.iceUfrag = line.slice('a=ice-ufrag:'.length);
} else if (ret.icePwd === '' && line.startsWith('a=ice-pwd:')) {
ret.icePwd = line.slice('a=ice-pwd:'.length);
for (const line of offer.split("\r\n")) {
if (line.startsWith("m=")) {
ret.medias.push(line.slice("m=".length));
} else if (ret.iceUfrag === "" && line.startsWith("a=ice-ufrag:")) {
ret.iceUfrag = line.slice("a=ice-ufrag:".length);
} else if (ret.icePwd === "" && line.startsWith("a=ice-pwd:")) {
ret.icePwd = line.slice("a=ice-pwd:".length);
}
}
@@ -119,18 +123,17 @@ class MediaMTXWebRTCPublisher {
candidatesByMedia[mid].push(candidate);
}
let frag = 'a=ice-ufrag:' + od.iceUfrag + '\r\n'
+ 'a=ice-pwd:' + od.icePwd + '\r\n';
let frag =
"a=ice-ufrag:" + od.iceUfrag + "\r\n" + "a=ice-pwd:" + od.icePwd + "\r\n";
let mid = 0;
for (const media of od.medias) {
if (candidatesByMedia[mid] !== undefined) {
frag += 'm=' + media + '\r\n'
+ 'a=mid:' + mid + '\r\n';
frag += "m=" + media + "\r\n" + "a=mid:" + mid + "\r\n";
for (const candidate of candidatesByMedia[mid]) {
frag += 'a=' + candidate.candidate + '\r\n';
frag += "a=" + candidate.candidate + "\r\n";
}
}
mid++;
@@ -140,16 +143,16 @@ class MediaMTXWebRTCPublisher {
}
static #setCodec(section, codec) {
const lines = section.split('\r\n');
const lines = section.split("\r\n");
const lines2 = [];
const payloadFormats = [];
for (const line of lines) {
if (!line.startsWith('a=rtpmap:')) {
if (!line.startsWith("a=rtpmap:")) {
lines2.push(line);
} else {
if (line.toLowerCase().includes(codec)) {
payloadFormats.push(line.slice('a=rtpmap:'.length).split(' ')[0]);
payloadFormats.push(line.slice("a=rtpmap:".length).split(" ")[0]);
lines2.push(line);
}
}
@@ -161,13 +164,19 @@ class MediaMTXWebRTCPublisher {
for (const line of lines2) {
if (firstLine) {
firstLine = false;
lines3.push(line.split(' ').slice(0, 3).concat(payloadFormats).join(' '));
} else if (line.startsWith('a=fmtp:')) {
if (payloadFormats.includes(line.slice('a=fmtp:'.length).split(' ')[0])) {
lines3.push(
line.split(" ").slice(0, 3).concat(payloadFormats).join(" "),
);
} else if (line.startsWith("a=fmtp:")) {
if (
payloadFormats.includes(line.slice("a=fmtp:".length).split(" ")[0])
) {
lines3.push(line);
}
} else if (line.startsWith('a=rtcp-fb:')) {
if (payloadFormats.includes(line.slice('a=rtcp-fb:'.length).split(' ')[0])) {
} else if (line.startsWith("a=rtcp-fb:")) {
if (
payloadFormats.includes(line.slice("a=rtcp-fb:".length).split(" ")[0])
) {
lines3.push(line);
}
} else {
@@ -175,76 +184,93 @@ class MediaMTXWebRTCPublisher {
}
}
return lines3.join('\r\n');
return lines3.join("\r\n");
}
static #setVideoBitrate(section, bitrate) {
let lines = section.split('\r\n');
let lines = section.split("\r\n");
for (let i = 0; i < lines.length; i++) {
if (lines[i].startsWith('c=')) {
lines = [...lines.slice(0, i+1), 'b=TIAS:' + (parseInt(bitrate) * 1024).toString(), ...lines.slice(i+1)];
break
}
}
return lines.join('\r\n');
}
static #setAudioBitrate(section, bitrate, voice) {
let opusPayloadFormat = '';
let lines = section.split('\r\n');
for (let i = 0; i < lines.length; i++) {
if (lines[i].startsWith('a=rtpmap:') && lines[i].toLowerCase().includes('opus/')) {
opusPayloadFormat = lines[i].slice('a=rtpmap:'.length).split(' ')[0];
if (lines[i].startsWith("c=")) {
lines = [
...lines.slice(0, i + 1),
"b=TIAS:" + (parseInt(bitrate) * 1024).toString(),
...lines.slice(i + 1),
];
break;
}
}
if (opusPayloadFormat === '') {
return lines.join("\r\n");
}
static #setAudioBitrate(section, bitrate, voice) {
let opusPayloadFormat = "";
let lines = section.split("\r\n");
for (let i = 0; i < lines.length; i++) {
if (
lines[i].startsWith("a=rtpmap:") &&
lines[i].toLowerCase().includes("opus/")
) {
opusPayloadFormat = lines[i].slice("a=rtpmap:".length).split(" ")[0];
break;
}
}
if (opusPayloadFormat === "") {
return section;
}
for (let i = 0; i < lines.length; i++) {
if (lines[i].startsWith('a=fmtp:' + opusPayloadFormat + ' ')) {
if (lines[i].startsWith("a=fmtp:" + opusPayloadFormat + " ")) {
if (voice) {
lines[i] = 'a=fmtp:' + opusPayloadFormat + ' minptime=10;useinbandfec=1;maxaveragebitrate='
+ (parseInt(bitrate) * 1024).toString();
lines[i] =
"a=fmtp:" +
opusPayloadFormat +
" minptime=10;useinbandfec=1;maxaveragebitrate=" +
(parseInt(bitrate) * 1024).toString();
} else {
lines[i] = 'a=fmtp:' + opusPayloadFormat + ' maxplaybackrate=48000;stereo=1;sprop-stereo=1;maxaveragebitrate='
+ (parseInt(bitrate) * 1024).toString();
lines[i] =
"a=fmtp:" +
opusPayloadFormat +
" maxplaybackrate=48000;stereo=1;sprop-stereo=1;maxaveragebitrate=" +
(parseInt(bitrate) * 1024).toString();
}
}
}
return lines.join('\r\n');
return lines.join("\r\n");
}
static #editOffer(sdp, videoCodec, audioCodec, audioBitrate, audioVoice) {
const sections = sdp.split('m=');
const sections = sdp.split("m=");
for (let i = 0; i < sections.length; i++) {
if (sections[i].startsWith('video')) {
if (sections[i].startsWith("video")) {
sections[i] = this.#setCodec(sections[i], videoCodec);
} else if (sections[i].startsWith('audio')) {
sections[i] = this.#setAudioBitrate(this.#setCodec(sections[i], audioCodec), audioBitrate, audioVoice);
} else if (sections[i].startsWith("audio")) {
sections[i] = this.#setAudioBitrate(
this.#setCodec(sections[i], audioCodec),
audioBitrate,
audioVoice,
);
}
}
return sections.join('m=');
return sections.join("m=");
}
static #editAnswer(sdp, videoBitrate) {
const sections = sdp.split('m=');
const sections = sdp.split("m=");
for (let i = 0; i < sections.length; i++) {
if (sections[i].startsWith('video')) {
if (sections[i].startsWith("video")) {
sections[i] = this.#setVideoBitrate(sections[i], videoBitrate);
}
}
return sections.join('m=');
return sections.join("m=");
}
#start() {
@@ -259,7 +285,7 @@ class MediaMTXWebRTCPublisher {
/** @param {string} err */
#handleError(err) {
if (this.#state === 'running') {
if (this.#state === "running") {
if (this.#pc !== null) {
this.#pc.close();
this.#pc = null;
@@ -269,17 +295,17 @@ class MediaMTXWebRTCPublisher {
if (this.#sessionUrl !== null) {
fetch(this.#sessionUrl, {
method: 'DELETE',
method: "DELETE",
});
this.#sessionUrl = null;
}
this.#queuedCandidates = [];
this.#state = 'restarting';
this.#state = "restarting";
this.#restartTimeout = window.setTimeout(() => {
this.#restartTimeout = null;
this.#state = 'running';
this.#state = "running";
this.#start();
}, this.#retryPause);
@@ -290,35 +316,36 @@ class MediaMTXWebRTCPublisher {
}
#authHeader() {
if (this.#conf.user !== undefined && this.#conf.user !== '') {
if (this.#conf.user !== undefined && this.#conf.user !== "") {
const credentials = btoa(`${this.#conf.user}:${this.#conf.pass}`);
return {'Authorization': `Basic ${credentials}`};
return { Authorization: `Basic ${credentials}` };
}
if (this.#conf.token !== undefined && this.#conf.token !== '') {
return {'Authorization': `Bearer ${this.#conf.token}`};
if (this.#conf.token !== undefined && this.#conf.token !== "") {
return { Authorization: `Bearer ${this.#conf.token}` };
}
return {};
}
#requestICEServers() {
return fetch(this.#conf.url, {
method: 'OPTIONS',
method: "OPTIONS",
headers: {
...this.#authHeader(),
},
})
.then((res) => MediaMTXWebRTCPublisher.#linkToIceServers(res.headers.get('Link')));
}).then((res) =>
MediaMTXWebRTCPublisher.#linkToIceServers(res.headers.get("Link")),
);
}
#setupPeerConnection(iceServers) {
if (this.#state !== 'running') {
throw new Error('closed');
if (this.#state !== "running") {
throw new Error("closed");
}
this.#pc = new RTCPeerConnection({
iceServers,
// https://webrtc.org/getting-started/unified-plan-transition-guide
sdpSemantics: 'unified-plan',
sdpSemantics: "unified-plan",
});
this.#pc.onicecandidate = (evt) => this.#onLocalCandidate(evt);
@@ -328,18 +355,16 @@ class MediaMTXWebRTCPublisher {
this.#pc.addTrack(track, this.#conf.stream);
});
return this.#pc.createOffer()
.then((offer) => {
this.#offerData = MediaMTXWebRTCPublisher.#parseOffer(offer.sdp);
return this.#pc.createOffer().then((offer) => {
this.#offerData = MediaMTXWebRTCPublisher.#parseOffer(offer.sdp);
return this.#pc.setLocalDescription(offer)
.then(() => offer.sdp);
});
return this.#pc.setLocalDescription(offer).then(() => offer.sdp);
});
}
#sendOffer(offer) {
if (this.#state !== 'running') {
throw new Error('closed');
if (this.#state !== "running") {
throw new Error("closed");
}
offer = MediaMTXWebRTCPublisher.#editOffer(
@@ -347,45 +372,56 @@ class MediaMTXWebRTCPublisher {
this.#conf.videoCodec,
this.#conf.audioCodec,
this.#conf.audioBitrate,
this.#conf.audioVoice);
this.#conf.audioVoice,
);
return fetch(this.#conf.url, {
method: 'POST',
method: "POST",
headers: {
...this.#authHeader(),
'Content-Type': 'application/sdp',
"Content-Type": "application/sdp",
},
body: offer,
})
.then((res) => {
switch (res.status) {
case 201:
break;
case 400:
return res.json().then((e) => { throw new Error(e.error); });
default:
throw new Error(`bad status code ${res.status}`);
}
}).then((res) => {
switch (res.status) {
case 201:
break;
case 400:
return res.json().then((e) => {
throw new Error(e.error);
});
default:
throw new Error(`bad status code ${res.status}`);
}
this.#sessionUrl = new URL(res.headers.get('location'), this.#conf.url).toString();
this.#sessionUrl = new URL(
res.headers.get("location"),
this.#conf.url,
).toString();
return res.text();
});
return res.text();
});
}
#setAnswer(answer) {
if (this.#state !== 'running') {
throw new Error('closed');
if (this.#state !== "running") {
throw new Error("closed");
}
answer = MediaMTXWebRTCPublisher.#editAnswer(answer, this.#conf.videoBitrate);
answer = MediaMTXWebRTCPublisher.#editAnswer(
answer,
this.#conf.videoBitrate,
);
return this.#pc.setRemoteDescription(new RTCSessionDescription({
type: 'answer',
sdp: answer,
}))
return this.#pc
.setRemoteDescription(
new RTCSessionDescription({
type: "answer",
sdp: answer,
}),
)
.then(() => {
if (this.#state !== 'running') {
if (this.#state !== "running") {
return;
}
@@ -397,7 +433,7 @@ class MediaMTXWebRTCPublisher {
}
#onLocalCandidate(evt) {
if (this.#state !== 'running') {
if (this.#state !== "running") {
return;
}
@@ -412,19 +448,22 @@ class MediaMTXWebRTCPublisher {
#sendLocalCandidates(candidates) {
fetch(this.#sessionUrl, {
method: 'PATCH',
method: "PATCH",
headers: {
'Content-Type': 'application/trickle-ice-sdpfrag',
'If-Match': '*',
"Content-Type": "application/trickle-ice-sdpfrag",
"If-Match": "*",
},
body: MediaMTXWebRTCPublisher.#generateSdpFragment(this.#offerData, candidates),
body: MediaMTXWebRTCPublisher.#generateSdpFragment(
this.#offerData,
candidates,
),
})
.then((res) => {
switch (res.status) {
case 204:
break;
case 404:
throw new Error('stream not found');
throw new Error("stream not found");
default:
throw new Error(`bad status code ${res.status}`);
}
@@ -435,7 +474,7 @@ class MediaMTXWebRTCPublisher {
}
#onConnectionState() {
if (this.#state !== 'running') {
if (this.#state !== "running") {
return;
}
@@ -443,17 +482,17 @@ class MediaMTXWebRTCPublisher {
// the close() method being called at all.
// It happens when the other peer sends a termination
// message like a DTLS CloseNotify.
if (this.#pc.connectionState === 'failed'
|| this.#pc.connectionState === 'closed'
if (
this.#pc.connectionState === "failed" ||
this.#pc.connectionState === "closed"
) {
this.#handleError('peer connection closed');
} else if (this.#pc.connectionState === 'connected') {
this.#handleError("peer connection closed");
} else if (this.#pc.connectionState === "connected") {
if (this.#conf.onConnected !== undefined) {
this.#conf.onConnected();
}
}
}
}
window.MediaMTXWebRTCPublisher = MediaMTXWebRTCPublisher;
+107 -107
View File
@@ -1,115 +1,115 @@
<!DOCTYPE html>
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width">
<style>
html, body {
margin: 0;
padding: 0;
height: 100%;
font-family: 'Arial', sans-serif;
}
#video {
position: absolute;
top: 0;
left: 0;
width: 100%;
height: 100%;
background: rgb(30, 30, 30);
}
#message {
position: absolute;
left: 0;
top: 0;
width: 100%;
height: 100%;
display: flex;
align-items: center;
text-align: center;
justify-content: center;
font-size: 16px;
font-weight: bold;
color: white;
pointer-events: none;
padding: 20px;
box-sizing: border-box;
text-shadow: 0 0 5px black;
}
</style>
<script defer src="./reader.js"></script>
</head>
<body>
<head>
<meta charset="utf-8" />
<meta name="viewport" content="width=device-width" />
<style>
html,
body {
margin: 0;
padding: 0;
height: 100%;
font-family: "Arial", sans-serif;
}
#video {
position: absolute;
top: 0;
left: 0;
width: 100%;
height: 100%;
background: rgb(30, 30, 30);
}
#message {
position: absolute;
left: 0;
top: 0;
width: 100%;
height: 100%;
display: flex;
align-items: center;
text-align: center;
justify-content: center;
font-size: 16px;
font-weight: bold;
color: white;
pointer-events: none;
padding: 20px;
box-sizing: border-box;
text-shadow: 0 0 5px black;
}
</style>
<script defer src="./reader.js"></script>
</head>
<body>
<video id="video"></video>
<div id="message"></div>
<video id="video"></video>
<div id="message"></div>
<script>
const video = document.getElementById("video");
const message = document.getElementById("message");
let defaultControls = false;
let reader = null;
<script>
const video = document.getElementById('video');
const message = document.getElementById('message');
let defaultControls = false;
let reader = null;
const setMessage = (str) => {
if (str !== '') {
video.controls = false;
} else {
video.controls = defaultControls;
}
message.innerText = str;
};
const parseBoolString = (str, defaultVal) => {
str = (str || '');
if (['1', 'yes', 'true'].includes(str.toLowerCase())) {
return true;
}
if (['0', 'no', 'false'].includes(str.toLowerCase())) {
return false;
}
return defaultVal;
};
const loadAttributesFromQuery = () => {
const params = new URLSearchParams(window.location.search);
video.controls = parseBoolString(params.get('controls'), true);
video.muted = parseBoolString(params.get('muted'), true);
video.autoplay = parseBoolString(params.get('autoplay'), true);
video.playsInline = parseBoolString(params.get('playsinline'), true);
video.disablepictureinpicture = parseBoolString(params.get('disablepictureinpicture'), false);
defaultControls = video.controls;
};
window.addEventListener('load', () => {
loadAttributesFromQuery();
reader = new MediaMTXWebRTCReader({
url: new URL('whep', window.location.href) + window.location.search,
onError: (err) => {
setMessage(err);
},
onTrack: (evt) => {
setMessage('');
video.srcObject = evt.streams[0];
},
onDataChannel: (evt) => {
evt.channel.binaryType = 'arraybuffer';
evt.channel.onmessage = (evt) => {
console.log('data channel message', evt.data);
const setMessage = (str) => {
if (str !== "") {
video.controls = false;
} else {
video.controls = defaultControls;
}
message.innerText = str;
};
},
});
});
window.addEventListener('beforeunload', () => {
if (reader !== null) {
reader.close();
}
});
const parseBoolString = (str, defaultVal) => {
str = str || "";
</script>
if (["1", "yes", "true"].includes(str.toLowerCase())) {
return true;
}
if (["0", "no", "false"].includes(str.toLowerCase())) {
return false;
}
return defaultVal;
};
</body>
const loadAttributesFromQuery = () => {
const params = new URLSearchParams(window.location.search);
video.controls = parseBoolString(params.get("controls"), true);
video.muted = parseBoolString(params.get("muted"), true);
video.autoplay = parseBoolString(params.get("autoplay"), true);
video.playsInline = parseBoolString(params.get("playsinline"), true);
video.disablepictureinpicture = parseBoolString(
params.get("disablepictureinpicture"),
false,
);
defaultControls = video.controls;
};
window.addEventListener("load", () => {
loadAttributesFromQuery();
reader = new MediaMTXWebRTCReader({
url: new URL("whep", window.location.href) + window.location.search,
onError: (err) => {
setMessage(err);
},
onTrack: (evt) => {
setMessage("");
video.srcObject = evt.streams[0];
},
onDataChannel: (evt) => {
evt.channel.binaryType = "arraybuffer";
evt.channel.onmessage = (evt) => {
console.log("data channel message", evt.data);
};
},
});
});
window.addEventListener("beforeunload", () => {
if (reader !== null) {
reader.close();
}
});
</script>
</body>
</html>
+245 -165
View File
@@ -1,4 +1,4 @@
'use strict';
"use strict";
/**
* @callback OnError
@@ -46,7 +46,7 @@ class MediaMTXWebRTCReader {
constructor(conf) {
this.#retryPause = 2000;
this.#conf = conf;
this.#state = 'getting_codecs';
this.#state = "getting_codecs";
this.#restartTimeout = null;
this.#pc = null;
this.#offerData = null;
@@ -59,7 +59,7 @@ class MediaMTXWebRTCReader {
* Close the reader and all its resources.
*/
close() {
this.#state = 'closed';
this.#state = "closed";
if (this.#pc !== null) {
this.#pc.close();
@@ -73,54 +73,59 @@ class MediaMTXWebRTCReader {
static #supportsNonAdvertisedCodec(codec, fmtp) {
return new Promise((resolve) => {
const pc = new RTCPeerConnection({ iceServers: [] });
const mediaType = 'audio';
let payloadType = '';
const mediaType = "audio";
let payloadType = "";
pc.addTransceiver(mediaType, { direction: 'recvonly' });
pc.addTransceiver(mediaType, { direction: "recvonly" });
pc.createOffer()
.then((offer) => {
if (offer.sdp === undefined) {
throw new Error('SDP not present');
throw new Error("SDP not present");
}
if (offer.sdp.includes(` ${codec}`)) { // codec is advertised, there's no need to add it manually
throw new Error('already present');
if (offer.sdp.includes(` ${codec}`)) {
// codec is advertised, there's no need to add it manually
throw new Error("already present");
}
const sections = offer.sdp.split(`m=${mediaType}`);
const payloadTypes = sections.slice(1)
.map((s) => s.split('\r\n')[0].split(' ').slice(3))
const payloadTypes = sections
.slice(1)
.map((s) => s.split("\r\n")[0].split(" ").slice(3))
.reduce((prev, cur) => [...prev, ...cur], []);
payloadType = this.#reservePayloadType(payloadTypes);
const lines = sections[1].split('\r\n');
const lines = sections[1].split("\r\n");
lines[0] += ` ${payloadType}`;
lines.splice(lines.length - 1, 0, `a=rtpmap:${payloadType} ${codec}`);
if (fmtp !== undefined) {
lines.splice(lines.length - 1, 0, `a=fmtp:${payloadType} ${fmtp}`);
}
sections[1] = lines.join('\r\n');
sections[1] = lines.join("\r\n");
offer.sdp = sections.join(`m=${mediaType}`);
return pc.setLocalDescription(offer);
})
.then(() => (
pc.setRemoteDescription(new RTCSessionDescription({
type: 'answer',
sdp: 'v=0\r\n'
+ 'o=- 6539324223450680508 0 IN IP4 0.0.0.0\r\n'
+ 's=-\r\n'
+ 't=0 0\r\n'
+ 'a=fingerprint:sha-256 0D:9F:78:15:42:B5:4B:E6:E2:94:3E:5B:37:78:E1:4B:54:59:A3:36:3A:E5:05:EB:27:EE:8F:D2:2D:41:29:25\r\n'
+ `m=${mediaType} 9 UDP/TLS/RTP/SAVPF ${payloadType}\r\n`
+ 'c=IN IP4 0.0.0.0\r\n'
+ 'a=ice-pwd:7c3bf4770007e7432ee4ea4d697db675\r\n'
+ 'a=ice-ufrag:29e036dc\r\n'
+ 'a=sendonly\r\n'
+ 'a=rtcp-mux\r\n'
+ `a=rtpmap:${payloadType} ${codec}\r\n`
+ ((fmtp !== undefined) ? `a=fmtp:${payloadType} ${fmtp}\r\n` : ''),
}))
))
.then(() =>
pc.setRemoteDescription(
new RTCSessionDescription({
type: "answer",
sdp:
"v=0\r\n" +
"o=- 6539324223450680508 0 IN IP4 0.0.0.0\r\n" +
"s=-\r\n" +
"t=0 0\r\n" +
"a=fingerprint:sha-256 0D:9F:78:15:42:B5:4B:E6:E2:94:3E:5B:37:78:E1:4B:54:59:A3:36:3A:E5:05:EB:27:EE:8F:D2:2D:41:29:25\r\n" +
`m=${mediaType} 9 UDP/TLS/RTP/SAVPF ${payloadType}\r\n` +
"c=IN IP4 0.0.0.0\r\n" +
"a=ice-pwd:7c3bf4770007e7432ee4ea4d697db675\r\n" +
"a=ice-ufrag:29e036dc\r\n" +
"a=sendonly\r\n" +
"a=rtcp-mux\r\n" +
`a=rtpmap:${payloadType} ${codec}\r\n` +
(fmtp !== undefined ? `a=fmtp:${payloadType} ${fmtp}\r\n` : ""),
}),
),
)
.then(() => {
resolve(true);
})
@@ -138,36 +143,40 @@ class MediaMTXWebRTCReader {
}
static #linkToIceServers(links) {
return (links !== null) ? links.split(', ').map((link) => {
const m = link.match(/^<(.+?)>; rel="ice-server"(; username="(.*?)"; credential="(.*?)"; credential-type="password")?/i);
const ret = {
urls: [m[1]],
};
return links !== null
? links.split(", ").map((link) => {
const m = link.match(
/^<(.+?)>; rel="ice-server"(; username="(.*?)"; credential="(.*?)"; credential-type="password")?/i,
);
const ret = {
urls: [m[1]],
};
if (m[3] !== undefined) {
ret.username = this.#unquoteCredential(m[3]);
ret.credential = this.#unquoteCredential(m[4]);
ret.credentialType = 'password';
}
if (m[3] !== undefined) {
ret.username = this.#unquoteCredential(m[3]);
ret.credential = this.#unquoteCredential(m[4]);
ret.credentialType = "password";
}
return ret;
}) : [];
return ret;
})
: [];
}
static #parseOffer(sdp) {
const ret = {
iceUfrag: '',
icePwd: '',
iceUfrag: "",
icePwd: "",
medias: [],
};
for (const line of sdp.split('\r\n')) {
if (line.startsWith('m=')) {
ret.medias.push(line.slice('m='.length));
} else if (ret.iceUfrag === '' && line.startsWith('a=ice-ufrag:')) {
ret.iceUfrag = line.slice('a=ice-ufrag:'.length);
} else if (ret.icePwd === '' && line.startsWith('a=ice-pwd:')) {
ret.icePwd = line.slice('a=ice-pwd:'.length);
for (const line of sdp.split("\r\n")) {
if (line.startsWith("m=")) {
ret.medias.push(line.slice("m=".length));
} else if (ret.iceUfrag === "" && line.startsWith("a=ice-ufrag:")) {
ret.iceUfrag = line.slice("a=ice-ufrag:".length);
} else if (ret.icePwd === "" && line.startsWith("a=ice-pwd:")) {
ret.icePwd = line.slice("a=ice-pwd:".length);
}
}
@@ -184,11 +193,11 @@ class MediaMTXWebRTCReader {
return pl;
}
}
throw Error('unable to find a free payload type');
throw Error("unable to find a free payload type");
}
static #enableStereoPcmau(payloadTypes, section) {
const lines = section.split('\r\n');
const lines = section.split("\r\n");
let payloadType = this.#reservePayloadType(payloadTypes);
lines[0] += ` ${payloadType}`;
@@ -200,53 +209,101 @@ class MediaMTXWebRTCReader {
lines.splice(lines.length - 1, 0, `a=rtpmap:${payloadType} PCMA/8000/2`);
lines.splice(lines.length - 1, 0, `a=rtcp-fb:${payloadType} transport-cc`);
return lines.join('\r\n');
return lines.join("\r\n");
}
static #enableMultichannelOpus(payloadTypes, section) {
const lines = section.split('\r\n');
const lines = section.split("\r\n");
let payloadType = this.#reservePayloadType(payloadTypes);
lines[0] += ` ${payloadType}`;
lines.splice(lines.length - 1, 0, `a=rtpmap:${payloadType} multiopus/48000/3`);
lines.splice(lines.length - 1, 0, `a=fmtp:${payloadType} channel_mapping=0,2,1;num_streams=2;coupled_streams=1`);
lines.splice(
lines.length - 1,
0,
`a=rtpmap:${payloadType} multiopus/48000/3`,
);
lines.splice(
lines.length - 1,
0,
`a=fmtp:${payloadType} channel_mapping=0,2,1;num_streams=2;coupled_streams=1`,
);
lines.splice(lines.length - 1, 0, `a=rtcp-fb:${payloadType} transport-cc`);
payloadType = this.#reservePayloadType(payloadTypes);
lines[0] += ` ${payloadType}`;
lines.splice(lines.length - 1, 0, `a=rtpmap:${payloadType} multiopus/48000/4`);
lines.splice(lines.length - 1, 0, `a=fmtp:${payloadType} channel_mapping=0,1,2,3;num_streams=2;coupled_streams=2`);
lines.splice(
lines.length - 1,
0,
`a=rtpmap:${payloadType} multiopus/48000/4`,
);
lines.splice(
lines.length - 1,
0,
`a=fmtp:${payloadType} channel_mapping=0,1,2,3;num_streams=2;coupled_streams=2`,
);
lines.splice(lines.length - 1, 0, `a=rtcp-fb:${payloadType} transport-cc`);
payloadType = this.#reservePayloadType(payloadTypes);
lines[0] += ` ${payloadType}`;
lines.splice(lines.length - 1, 0, `a=rtpmap:${payloadType} multiopus/48000/5`);
lines.splice(lines.length - 1, 0, `a=fmtp:${payloadType} channel_mapping=0,4,1,2,3;num_streams=3;coupled_streams=2`);
lines.splice(
lines.length - 1,
0,
`a=rtpmap:${payloadType} multiopus/48000/5`,
);
lines.splice(
lines.length - 1,
0,
`a=fmtp:${payloadType} channel_mapping=0,4,1,2,3;num_streams=3;coupled_streams=2`,
);
lines.splice(lines.length - 1, 0, `a=rtcp-fb:${payloadType} transport-cc`);
payloadType = this.#reservePayloadType(payloadTypes);
lines[0] += ` ${payloadType}`;
lines.splice(lines.length - 1, 0, `a=rtpmap:${payloadType} multiopus/48000/6`);
lines.splice(lines.length - 1, 0, `a=fmtp:${payloadType} channel_mapping=0,4,1,2,3,5;num_streams=4;coupled_streams=2`);
lines.splice(
lines.length - 1,
0,
`a=rtpmap:${payloadType} multiopus/48000/6`,
);
lines.splice(
lines.length - 1,
0,
`a=fmtp:${payloadType} channel_mapping=0,4,1,2,3,5;num_streams=4;coupled_streams=2`,
);
lines.splice(lines.length - 1, 0, `a=rtcp-fb:${payloadType} transport-cc`);
payloadType = this.#reservePayloadType(payloadTypes);
lines[0] += ` ${payloadType}`;
lines.splice(lines.length - 1, 0, `a=rtpmap:${payloadType} multiopus/48000/7`);
lines.splice(lines.length - 1, 0, `a=fmtp:${payloadType} channel_mapping=0,4,1,2,3,5,6;num_streams=4;coupled_streams=4`);
lines.splice(
lines.length - 1,
0,
`a=rtpmap:${payloadType} multiopus/48000/7`,
);
lines.splice(
lines.length - 1,
0,
`a=fmtp:${payloadType} channel_mapping=0,4,1,2,3,5,6;num_streams=4;coupled_streams=4`,
);
lines.splice(lines.length - 1, 0, `a=rtcp-fb:${payloadType} transport-cc`);
payloadType = this.#reservePayloadType(payloadTypes);
lines[0] += ` ${payloadType}`;
lines.splice(lines.length - 1, 0, `a=rtpmap:${payloadType} multiopus/48000/8`);
lines.splice(lines.length - 1, 0, `a=fmtp:${payloadType} channel_mapping=0,6,1,4,5,2,3,7;num_streams=5;coupled_streams=4`);
lines.splice(
lines.length - 1,
0,
`a=rtpmap:${payloadType} multiopus/48000/8`,
);
lines.splice(
lines.length - 1,
0,
`a=fmtp:${payloadType} channel_mapping=0,6,1,4,5,2,3,7;num_streams=5;coupled_streams=4`,
);
lines.splice(lines.length - 1, 0, `a=rtcp-fb:${payloadType} transport-cc`);
return lines.join('\r\n');
return lines.join("\r\n");
}
static #enableL16(payloadTypes, section) {
const lines = section.split('\r\n');
const lines = section.split("\r\n");
let payloadType = this.#reservePayloadType(payloadTypes);
lines[0] += ` ${payloadType}`;
@@ -263,56 +320,60 @@ class MediaMTXWebRTCReader {
lines.splice(lines.length - 1, 0, `a=rtpmap:${payloadType} L16/48000/2`);
lines.splice(lines.length - 1, 0, `a=rtcp-fb:${payloadType} transport-cc`);
return lines.join('\r\n');
return lines.join("\r\n");
}
static #enableStereoOpus(section) {
let opusPayloadFormat = '';
const lines = section.split('\r\n');
let opusPayloadFormat = "";
const lines = section.split("\r\n");
for (let i = 0; i < lines.length; i++) {
if (lines[i].startsWith('a=rtpmap:') && lines[i].toLowerCase().includes('opus/')) {
opusPayloadFormat = lines[i].slice('a=rtpmap:'.length).split(' ')[0];
if (
lines[i].startsWith("a=rtpmap:") &&
lines[i].toLowerCase().includes("opus/")
) {
opusPayloadFormat = lines[i].slice("a=rtpmap:".length).split(" ")[0];
break;
}
}
if (opusPayloadFormat === '') {
if (opusPayloadFormat === "") {
return section;
}
for (let i = 0; i < lines.length; i++) {
if (lines[i].startsWith(`a=fmtp:${opusPayloadFormat} `)) {
if (!lines[i].includes('stereo')) {
lines[i] += ';stereo=1';
if (!lines[i].includes("stereo")) {
lines[i] += ";stereo=1";
}
if (!lines[i].includes('sprop-stereo')) {
lines[i] += ';sprop-stereo=1';
if (!lines[i].includes("sprop-stereo")) {
lines[i] += ";sprop-stereo=1";
}
}
}
return lines.join('\r\n');
return lines.join("\r\n");
}
static #editOffer(sdp, nonAdvertisedCodecs) {
const sections = sdp.split('m=');
const sections = sdp.split("m=");
const payloadTypes = sections.slice(1)
.map((s) => s.split('\r\n')[0].split(' ').slice(3))
const payloadTypes = sections
.slice(1)
.map((s) => s.split("\r\n")[0].split(" ").slice(3))
.reduce((prev, cur) => [...prev, ...cur], []);
for (let i = 1; i < sections.length; i++) {
if (sections[i].startsWith('audio')) {
if (sections[i].startsWith("audio")) {
sections[i] = this.#enableStereoOpus(sections[i]);
if (nonAdvertisedCodecs.includes('pcma/8000/2')) {
if (nonAdvertisedCodecs.includes("pcma/8000/2")) {
sections[i] = this.#enableStereoPcmau(payloadTypes, sections[i]);
}
if (nonAdvertisedCodecs.includes('multiopus/48000/6')) {
if (nonAdvertisedCodecs.includes("multiopus/48000/6")) {
sections[i] = this.#enableMultichannelOpus(payloadTypes, sections[i]);
}
if (nonAdvertisedCodecs.includes('L16/48000/2')) {
if (nonAdvertisedCodecs.includes("L16/48000/2")) {
sections[i] = this.#enableL16(payloadTypes, sections[i]);
}
@@ -320,7 +381,7 @@ class MediaMTXWebRTCReader {
}
}
return sections.join('m=');
return sections.join("m=");
}
static #generateSdpFragment(od, candidates) {
@@ -333,15 +394,13 @@ class MediaMTXWebRTCReader {
candidatesByMedia[mid].push(candidate);
}
let frag = `a=ice-ufrag:${od.iceUfrag}\r\n`
+ `a=ice-pwd:${od.icePwd}\r\n`;
let frag = `a=ice-ufrag:${od.iceUfrag}\r\n` + `a=ice-pwd:${od.icePwd}\r\n`;
let mid = 0;
for (const media of od.medias) {
if (candidatesByMedia[mid] !== undefined) {
frag += `m=${media}\r\n`
+ `a=mid:${mid}\r\n`;
frag += `m=${media}\r\n` + `a=mid:${mid}\r\n`;
for (const candidate of candidatesByMedia[mid]) {
frag += `a=${candidate.candidate}\r\n`;
@@ -355,7 +414,7 @@ class MediaMTXWebRTCReader {
/** @param {string} err */
#handleError(err) {
if (this.#state === 'running') {
if (this.#state === "running") {
if (this.#pc !== null) {
this.#pc.close();
this.#pc = null;
@@ -365,25 +424,25 @@ class MediaMTXWebRTCReader {
if (this.#sessionUrl !== null) {
fetch(this.#sessionUrl, {
method: 'DELETE',
method: "DELETE",
});
this.#sessionUrl = null;
}
this.#queuedCandidates = [];
this.#state = 'restarting';
this.#state = "restarting";
this.#restartTimeout = window.setTimeout(() => {
this.#restartTimeout = null;
this.#state = 'running';
this.#state = "running";
this.#start();
}, this.#retryPause);
if (this.#conf.onError !== undefined) {
this.#conf.onError(`${err}, retrying in some seconds`);
}
} else if (this.#state === 'getting_codecs') {
this.#state = 'failed';
} else if (this.#state === "getting_codecs") {
this.#state = "failed";
if (this.#conf.onError !== undefined) {
this.#conf.onError(err);
@@ -392,20 +451,28 @@ class MediaMTXWebRTCReader {
}
#getNonAdvertisedCodecs() {
Promise.all([
['pcma/8000/2'],
['multiopus/48000/6', 'channel_mapping=0,4,1,2,3,5;num_streams=4;coupled_streams=2'],
['L16/48000/2'],
]
.map((c) => MediaMTXWebRTCReader.#supportsNonAdvertisedCodec(c[0], c[1]).then((r) => ((r) ? c[0] : false))))
Promise.all(
[
["pcma/8000/2"],
[
"multiopus/48000/6",
"channel_mapping=0,4,1,2,3,5;num_streams=4;coupled_streams=2",
],
["L16/48000/2"],
].map((c) =>
MediaMTXWebRTCReader.#supportsNonAdvertisedCodec(c[0], c[1]).then(
(r) => (r ? c[0] : false),
),
),
)
.then((c) => c.filter((e) => e !== false))
.then((codecs) => {
if (this.#state !== 'getting_codecs') {
throw new Error('closed');
if (this.#state !== "getting_codecs") {
throw new Error("closed");
}
this.#nonAdvertisedCodecs = codecs;
this.#state = 'running';
this.#state = "running";
this.#start();
})
.catch((err) => {
@@ -424,101 +491,110 @@ class MediaMTXWebRTCReader {
}
#authHeader() {
if (this.#conf.user !== undefined && this.#conf.user !== '') {
if (this.#conf.user !== undefined && this.#conf.user !== "") {
const credentials = btoa(`${this.#conf.user}:${this.#conf.pass}`);
return {'Authorization': `Basic ${credentials}`};
return { Authorization: `Basic ${credentials}` };
}
if (this.#conf.token !== undefined && this.#conf.token !== '') {
return {'Authorization': `Bearer ${this.#conf.token}`};
if (this.#conf.token !== undefined && this.#conf.token !== "") {
return { Authorization: `Bearer ${this.#conf.token}` };
}
return {};
}
#requestICEServers() {
return fetch(this.#conf.url, {
method: 'OPTIONS',
method: "OPTIONS",
headers: {
...this.#authHeader(),
},
})
.then((res) => MediaMTXWebRTCReader.#linkToIceServers(res.headers.get('Link')));
}).then((res) =>
MediaMTXWebRTCReader.#linkToIceServers(res.headers.get("Link")),
);
}
#setupPeerConnection(iceServers) {
if (this.#state !== 'running') {
throw new Error('closed');
if (this.#state !== "running") {
throw new Error("closed");
}
this.#pc = new RTCPeerConnection({
iceServers,
// https://webrtc.org/getting-started/unified-plan-transition-guide
sdpSemantics: 'unified-plan',
sdpSemantics: "unified-plan",
});
const direction = 'recvonly';
this.#pc.addTransceiver('video', { direction });
this.#pc.addTransceiver('audio', { direction });
const direction = "recvonly";
this.#pc.addTransceiver("video", { direction });
this.#pc.addTransceiver("audio", { direction });
// using data channels requires creating a data channel locally
this.#pc.createDataChannel('');
this.#pc.createDataChannel("");
this.#pc.onicecandidate = (evt) => this.#onLocalCandidate(evt);
this.#pc.onconnectionstatechange = () => this.#onConnectionState();
this.#pc.ontrack = (evt) => this.#onTrack(evt);
this.#pc.ondatachannel = (evt) => this.#onDataChannel(evt);
return this.#pc.createOffer()
.then((offer) => {
offer.sdp = MediaMTXWebRTCReader.#editOffer(offer.sdp, this.#nonAdvertisedCodecs);
this.#offerData = MediaMTXWebRTCReader.#parseOffer(offer.sdp);
return this.#pc.createOffer().then((offer) => {
offer.sdp = MediaMTXWebRTCReader.#editOffer(
offer.sdp,
this.#nonAdvertisedCodecs,
);
this.#offerData = MediaMTXWebRTCReader.#parseOffer(offer.sdp);
return this.#pc.setLocalDescription(offer)
.then(() => offer.sdp);
});
return this.#pc.setLocalDescription(offer).then(() => offer.sdp);
});
}
#sendOffer(offer) {
if (this.#state !== 'running') {
throw new Error('closed');
if (this.#state !== "running") {
throw new Error("closed");
}
return fetch(this.#conf.url, {
method: 'POST',
method: "POST",
headers: {
...this.#authHeader(),
'Content-Type': 'application/sdp',
"Content-Type": "application/sdp",
},
body: offer,
})
.then((res) => {
switch (res.status) {
case 201:
break;
case 404:
throw new Error('stream not found');
case 400:
return res.json().then((e) => { throw new Error(e.error); });
default:
throw new Error(`bad status code ${res.status}`);
}
}).then((res) => {
switch (res.status) {
case 201:
break;
case 404:
throw new Error("stream not found");
case 400:
return res.json().then((e) => {
throw new Error(e.error);
});
default:
throw new Error(`bad status code ${res.status}`);
}
this.#sessionUrl = new URL(res.headers.get('location'), this.#conf.url).toString();
this.#sessionUrl = new URL(
res.headers.get("location"),
this.#conf.url,
).toString();
return res.text();
});
return res.text();
});
}
#setAnswer(answer) {
if (this.#state !== 'running') {
throw new Error('closed');
if (this.#state !== "running") {
throw new Error("closed");
}
return this.#pc.setRemoteDescription(new RTCSessionDescription({
type: 'answer',
sdp: answer,
}))
return this.#pc
.setRemoteDescription(
new RTCSessionDescription({
type: "answer",
sdp: answer,
}),
)
.then(() => {
if (this.#state !== 'running') {
if (this.#state !== "running") {
return;
}
@@ -530,7 +606,7 @@ class MediaMTXWebRTCReader {
}
#onLocalCandidate(evt) {
if (this.#state !== 'running') {
if (this.#state !== "running") {
return;
}
@@ -545,19 +621,22 @@ class MediaMTXWebRTCReader {
#sendLocalCandidates(candidates) {
fetch(this.#sessionUrl, {
method: 'PATCH',
method: "PATCH",
headers: {
'Content-Type': 'application/trickle-ice-sdpfrag',
'If-Match': '*',
"Content-Type": "application/trickle-ice-sdpfrag",
"If-Match": "*",
},
body: MediaMTXWebRTCReader.#generateSdpFragment(this.#offerData, candidates),
body: MediaMTXWebRTCReader.#generateSdpFragment(
this.#offerData,
candidates,
),
})
.then((res) => {
switch (res.status) {
case 204:
break;
case 404:
throw new Error('stream not found');
throw new Error("stream not found");
default:
throw new Error(`bad status code ${res.status}`);
}
@@ -568,7 +647,7 @@ class MediaMTXWebRTCReader {
}
#onConnectionState() {
if (this.#state !== 'running') {
if (this.#state !== "running") {
return;
}
@@ -576,10 +655,11 @@ class MediaMTXWebRTCReader {
// the close() method being called at all.
// It happens when the other peer sends a termination
// message like a DTLS CloseNotify.
if (this.#pc.connectionState === 'failed'
|| this.#pc.connectionState === 'closed'
if (
this.#pc.connectionState === "failed" ||
this.#pc.connectionState === "closed"
) {
this.#handleError('peer connection closed');
this.#handleError("peer connection closed");
}
}