perfect negotiation 2 best firefox w/logging
by jib1
JavaScript
async function peer(other, polite, width = 160, height = 120) {
// This creates all the buttons. You can skip this part
const create = (container, type) => container.appendChild(document.createElement(type));
const body = create(document.documentElement, "body");
const camera = createCheckbox("Camera"), noise = createCheckbox("Noise");
const both = polite && createCheckbox("Both noise");
function createCheckbox(textContent) {
const label = create(body, "label");
const input = Object.assign(create(label, "input"), {type: "checkbox"});
Object.assign(create(label, "text"), {textContent});
return input;
}
const div = create(body, "div");
const log = msg => {
const s = `${performance.now().toFixed()}: ${msg}`;
console.log(`${polite? "" : "im"}polite: ${s}`);
// div.innerHTML += `${s}<br>`;
return s;
}
const logerr = msg => div.innerHTML += `${log(msg)}<br>`;
const send = msg => other.postMessage(JSON.parse(JSON.stringify(msg)), "*");
// This is the main application logic
try {
const pc = new RTCPeerConnection();
const dc = pc.createDataChannel("both", {negotiated: true, id: 0});
camera.onclick = () => onOff(camera, () => navigator.mediaDevices.getUserMedia({video: true}));
noise.onclick = () => onOff(noise, whiteNoise);
both.onclick = () => { dc.send(both.checked); dc.onmessage({data: both.checked}); }
dc.onmessage = ({data}) => noise.checked == JSON.parse(data) || noise.click();
async function onOff(button, getMedia) {
try {
if (button.checked) {
if (!button.stream) button.stream = await getMedia();
button.transceiver = pc.addTransceiver(button.stream.getTracks()[0], {streams: [button.stream]});
} else {
button.transceiver.stop();
}
} catch (e) {
logerr(e);
}
}
pc.ontrack = ({streams: [stream]}) => {
if (!stream.video) {
stream.video = Object.assign(create(body, "video"),...