LordOS — a free, fast and secure GNU/Linux distribution based on Debian, with its own desktop environment: display server and Wayland compositor in C, a React UI engine on QuickJS, and private native apps.
C cdebiandesktop-environmentebpffirewalllandlocklinuxlinux-distributionopen-sourceprivacyquickjsraspberry-pi-5reactsecuritywaylandwayland-compositor
<!doctype html>
<html lang="en" translate="no">
<head>
<meta charset="utf-8">
<meta name="google" content="notranslate">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>LordOS · Remote desktop</title>
<style>
* { box-sizing: border-box; }
html, body { margin: 0; height: 100%; background: #0b0a14; overflow: hidden; font: 13px system-ui, -apple-system, "Segoe UI", sans-serif; color: #eee; }
#wrap { position: fixed; inset: 0; display: grid; place-items: center; }
#stage { position: relative; }
canvas { position: absolute; inset: 0; display: block; image-rendering: auto; outline: none; touch-action: none; }
video { position: absolute; inset: 0; display: block; visibility: hidden; background: #000; pointer-events: none; }
#bar { position: fixed; top: 0; left: 50%; transform: translate(-50%, -34px); transition: transform .18s ease; z-index: 3;
display: flex; gap: 10px; align-items: center; padding: 6px 10px 6px 12px; border-radius: 0 0 12px 12px;
background: rgba(28,26,44,.92); border: 1px solid rgba(255,255,255,.12); border-top: 0; white-space: nowrap; }
#bar.show, #bar:hover, #bar.pinned { transform: translate(-50%, 0); }
#bar button.on { background: #6d4aff; }
#bar button { border: 0; border-radius: 7px; padding: 5px 10px; color: #fff; background: #3a3754; cursor: pointer; font-size: 12px; }
#bar button.red { background: #b4232f; }
#lat { color: #a9a6c3; min-width: 52px; }
#mode { color: #a9a6c3; }
#again-note { position: fixed; top: 12px; left: 50%; transform: translateX(-50%); z-index: 4; display: none; padding: 7px 14px;
border-radius: 16px; background: rgba(28,26,44,.94); border: 1px solid rgba(255,255,255,.16); color: #fff; }
#again-note i { display: inline-block; width: 10px; height: 10px; margin-inline-end: 8px; border-radius: 50%;
border: 2px solid #a77bf3; border-top-color: transparent; animation: spin 0.9s linear infinite; vertical-align: -1px; }
@keyframes spin { to { transform: rotate(360deg); } }
#msg { position: fixed; inset: 0; display: none; place-items: center; z-index: 5; background: rgba(8,8,16,.88); padding: 16px; }
#card { width: min(560px, 100%); max-height: calc(100vh - 32px); overflow: auto; padding: 22px 26px; border-radius: 14px;
background: #1f1c33; border: 1px solid rgba(255,255,255,.14); line-height: 1.45; }
#card h1 { margin: 0 0 8px; font-size: 18px; font-weight: 650; color: #fff; }
#card p { margin: 6px 0; color: #d8d5ea; }
#card ul { margin: 6px 0 4px; padding-inline-start: 4px; list-style: none; color: #d8d5ea; }
#card li { margin: 3px 0; }
#card li.no { color: #ffb4b4; }
#card .what { margin-top: 12px; padding: 10px 12px; border-radius: 10px; background: rgba(167,123,243,.12); color: #ece6ff; }
#card .det { margin-top: 10px; font: 11px ui-monospace, Menlo, monospace; color: #8f8ba8; word-break: break-word; }
#card .btns { display: flex; gap: 8px; justify-content: flex-end; margin-top: 16px; flex-wrap: wrap; }
#card button { border: 0; border-radius: 8px; padding: 8px 16px; color: #fff; background: #6d28d9; cursor: pointer; font-size: 13px; }
#card button.plain { background: #3a3754; }
#card .spin { display: inline-block; width: 14px; height: 14px; margin-inline-end: 10px; border-radius: 50%; border: 2px solid #a77bf3;
border-top-color: transparent; animation: spin 0.9s linear infinite; vertical-align: -2px; }
#rcur { position: fixed; width: 14px; height: 20px; pointer-events: none; display: none; z-index: 2;
background: no-repeat url("data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' width='14' height='20'%3E%3Cpath d='M1 1v16l4-4 3 6 2-1-3-6h6z' fill='white' stroke='black'/%3E%3C/svg%3E"); }
</style>
</head>
<body>
<div id="wrap"><div id="stage"><video id="v" autoplay playsinline muted></video><canvas id="c" tabindex="0"></canvas></div></div>
<div id="rcur"></div>
<div id="bar"><span id="who">LordOS</span><span id="lat">…</span><span id="mode"></span>
<button id="snd" hidden>🔇</button><button id="pin">📌</button><button id="fs">⛶</button><button id="out" class="red">✕</button></div>
<div id="again-note"><i></i><span id="again-text"></span></div>
<div id="msg"><div id="card" role="alertdialog" aria-live="assertive"></div></div>
<script>
'use strict';
// The remote desktop arrives only as WebRTC video (docs/REMOTE.md, "Video (WebRTC)"). If the
// connection breaks, the page restarts ICE, then makes a new peer, then reconnects the WebSocket, on
// its own and without signing in again; if it truly can't connect, it says why and what to do.
const L = {
en: {
full: 'Full screen', out: 'Disconnect', conn: 'Connecting…', reconn: 'Reconnecting…', retry: 'Try again', signout: 'Sign out',
sndOn: 'Turn sound on', sndOff: 'Turn sound off', video: 'Video', bye: 'The session ended.',
hwEnc: 'hardware', swEnc: 'software', pinOn: 'Keep this bar shown', pinOff: 'Let this bar hide',
vinfoTip: (comp, enc, ms) => `Screen composed on the ${comp}; video encoded in ${enc} (${ms} ms per frame). Frames a second: shown here / sent by the computer.`,
unsupTitle: 'This browser can’t show the remote desktop',
unsupText: 'The remote desktop arrives as live video over WebRTC. This browser is missing something it needs:',
reqRtc: 'WebRTC (RTCPeerConnection) with data channels', reqCodec: 'H.264 or VP8 video decoding', reqSecure: 'A secure (https) page — this one is',
unsupWhat: 'Open this address in an up-to-date desktop or mobile browser with WebRTC turned on. Privacy extensions or settings that turn WebRTC off also cause this.',
failTitle: 'Couldn’t connect to the remote desktop', why: 'Why', what: 'What to do', details: 'Details',
noroute: 'The video connection never reached this computer: no connection check arrived over UDP, nor over TCP port {port}. A firewall, a VPN or the network between you is blocking both.',
norouteWhat: 'Allow UDP, or at least TCP port {port}, between this browser and the computer. To connect across networks, an administrator can add a relay (TURN) in Settings → Sharing on the computer.',
dtls: 'The connection was reached, but the encrypted video channel (DTLS) couldn’t be set up.',
dtlsWhat: 'Try again. If it keeps happening, something between you (a proxy or security software) is altering the connection.',
lost: 'The connection was lost and didn’t come back.', lostWhat: 'Check the network on both sides. When it is back, try again: you stay signed in.',
server: 'The computer couldn’t start the video connection.', serverWhat: 'Try again. If it keeps happening, turn the remote desktop off and on in Settings → Sharing.',
offer: 'The computer refused or didn’t answer this browser’s connection offer.', offerWhat: 'Update the browser and try again. If it keeps happening, an extension may be changing the page.',
media: 'The connection is up, but no picture arrived.', mediaWhat: 'This browser may not be able to play H.264 or VP8 video right now (hardware decoding turned off, or a codec blocked). Try another browser.',
wsdown: 'The computer can’t be reached: the connection to it was lost.', wsdownWhat: 'Check that the computer is on and on the network. This page keeps trying on its own.',
},
es: {
full: 'Pantalla completa', out: 'Desconectar', conn: 'Conectando…', reconn: 'Reconectando…', retry: 'Reintentar', signout: 'Cerrar sesión',
sndOn: 'Activar el sonido', sndOff: 'Silenciar', video: 'Video', bye: 'La sesión terminó.',
hwEnc: 'por hardware', swEnc: 'por software', pinOn: 'Dejar la barra fija', pinOff: 'Que la barra se esconda',
vinfoTip: (comp, enc, ms) => `Pantalla compuesta en la ${comp}; video codificado ${enc} (${ms} ms por cuadro). Cuadros por segundo: mostrados aquí / enviados por la computadora.`,
unsupTitle: 'Este navegador no puede mostrar el escritorio remoto',
unsupText: 'El escritorio remoto llega como video en vivo por WebRTC. A este navegador le falta algo que necesita:',
reqRtc: 'WebRTC (RTCPeerConnection) con canales de datos', reqCodec: 'Decodificar video H.264 o VP8', reqSecure: 'Una página segura (https): esta lo es',
unsupWhat: 'Abrí esta dirección en un navegador actualizado, de escritorio o del teléfono, con WebRTC activado. Las extensiones o ajustes de privacidad que apagan WebRTC también causan esto.',
failTitle: 'No se pudo conectar al escritorio remoto', why: 'Por qué', what: 'Qué hacer', details: 'Detalles',
noroute: 'La conexión de video nunca llegó a esta computadora: no llegó ninguna comprobación de conexión por UDP ni por el puerto TCP {port}. Un firewall, una VPN o la red entre ustedes bloquea los dos.',
norouteWhat: 'Permití UDP, o al menos el puerto TCP {port}, entre este navegador y la computadora. Para conectarse entre redes distintas, un administrador puede agregar un relé (TURN) en Ajustes → Compartir de la computadora.',
dtls: 'La conexión llegó, pero no se pudo establecer el canal de video cifrado (DTLS).',
dtlsWhat: 'Reintentá. Si sigue pasando, algo entre ustedes (un proxy o un programa de seguridad) está alterando la conexión.',
lost: 'La conexión se cortó y no volvió.', lostWhat: 'Revisá la red de los dos lados. Cuando vuelva, reintentá: la sesión sigue iniciada.',
server: 'La computadora no pudo iniciar la conexión de video.', serverWhat: 'Reintentá. Si sigue pasando, apagá y encendé el escritorio remoto en Ajustes → Compartir.',
offer: 'La computadora rechazó o no respondió la propuesta de conexión de este navegador.', offerWhat: 'Actualizá el navegador y reintentá. Si sigue pasando, puede que una extensión esté modificando la página.',
media: 'La conexión está establecida, pero no llegó imagen.', mediaWhat: 'Puede que este navegador no pueda reproducir video H.264 o VP8 ahora (decodificación por hardware apagada o un códec bloqueado). Probá con otro navegador.',
wsdown: 'No se puede llegar a la computadora: se perdió la conexión.', wsdownWhat: 'Comprobá que la computadora esté encendida y en la red. Esta página sigue intentando sola.',
},
pt: {
full: 'Tela cheia', out: 'Desconectar', conn: 'Conectando…', reconn: 'Reconectando…', retry: 'Tentar de novo', signout: 'Sair',
sndOn: 'Ativar o som', sndOff: 'Silenciar', video: 'Vídeo', bye: 'A sessão terminou.',
hwEnc: 'por hardware', swEnc: 'por software', pinOn: 'Fixar a barra', pinOff: 'Deixar a barra se esconder',
vinfoTip: (comp, enc, ms) => `Tela composta na ${comp}; vídeo codificado ${enc} (${ms} ms por quadro). Quadros por segundo: mostrados aqui / enviados pelo computador.`,
unsupTitle: 'Este navegador não consegue mostrar a área de trabalho remota',
unsupText: 'A área de trabalho remota chega como vídeo ao vivo por WebRTC. Falta a este navegador algo de que ela precisa:',
reqRtc: 'WebRTC (RTCPeerConnection) com canais de dados', reqCodec: 'Decodificar vídeo H.264 ou VP8', reqSecure: 'Uma página segura (https): esta é',
unsupWhat: 'Abra este endereço em um navegador atualizado, de computador ou celular, com o WebRTC ativado. Extensões ou ajustes de privacidade que desligam o WebRTC também causam isso.',
failTitle: 'Não foi possível conectar à área de trabalho remota', why: 'Por quê', what: 'O que fazer', details: 'Detalhes',
noroute: 'A conexão de vídeo nunca chegou a este computador: nenhuma verificação de conexão chegou por UDP nem pela porta TCP {port}. Um firewall, uma VPN ou a rede entre vocês bloqueia as duas.',
norouteWhat: 'Permita UDP, ou pelo menos a porta TCP {port}, entre este navegador e o computador. Para conectar entre redes diferentes, um administrador pode adicionar um retransmissor (TURN) em Ajustes → Compartilhar no computador.',
dtls: 'A conexão chegou, mas o canal de vídeo criptografado (DTLS) não pôde ser estabelecido.',
dtlsWhat: 'Tente de novo. Se continuar, algo entre vocês (um proxy ou um programa de segurança) está alterando a conexão.',
lost: 'A conexão caiu e não voltou.', lostWhat: 'Verifique a rede dos dois lados. Quando voltar, tente de novo: a sessão continua iniciada.',
server: 'O computador não conseguiu iniciar a conexão de vídeo.', serverWhat: 'Tente de novo. Se continuar, desligue e ligue a área de trabalho remota em Ajustes → Compartilhar.',
offer: 'O computador recusou ou não respondeu a proposta de conexão deste navegador.', offerWhat: 'Atualize o navegador e tente de novo. Se continuar, uma extensão pode estar modificando a página.',
media: 'A conexão está estabelecida, mas nenhuma imagem chegou.', mediaWhat: 'Este navegador talvez não consiga reproduzir vídeo H.264 ou VP8 agora (decodificação por hardware desligada ou um codec bloqueado). Tente outro navegador.',
wsdown: 'Não é possível alcançar o computador: a conexão caiu.', wsdownWhat: 'Verifique se o computador está ligado e na rede. Esta página continua tentando sozinha.',
},
};
const T = L[(navigator.language || 'en').slice(0, 2)] || L.en;
const $ = (id) => document.getElementById(id);
const cv = $('c'), ctx = cv.getContext('2d'), vid = $('v'), stage = $('stage');
const PORT = location.port || '443';
$('fs').title = T.full; $('out').title = T.out;
// what the page knows, for tests and support: state, the last reason, the media path
const rd = window.__rd = { state: 'start', why: '', path: '', restarts: 0, peers: 0, wsOpens: 0 };
// KeyboardEvent.code → evdev code (linux/input-event-codes.h)
const K = { Escape: 1, Digit1: 2, Digit2: 3, Digit3: 4, Digit4: 5, Digit5: 6, Digit6: 7, Digit7: 8, Digit8: 9, Digit9: 10, Digit0: 11,
Minus: 12, Equal: 13, Backspace: 14, Tab: 15, KeyQ: 16, KeyW: 17, KeyE: 18, KeyR: 19, KeyT: 20, KeyY: 21, KeyU: 22, KeyI: 23,
KeyO: 24, KeyP: 25, BracketLeft: 26, BracketRight: 27, Enter: 28, ControlLeft: 29, KeyA: 30, KeyS: 31, KeyD: 32, KeyF: 33,
KeyG: 34, KeyH: 35, KeyJ: 36, KeyK: 37, KeyL: 38, Semicolon: 39, Quote: 40, Backquote: 41, ShiftLeft: 42, Backslash: 43,
KeyZ: 44, KeyX: 45, KeyC: 46, KeyV: 47, KeyB: 48, KeyN: 49, KeyM: 50, Comma: 51, Period: 52, Slash: 53, ShiftRight: 54,
NumpadMultiply: 55, AltLeft: 56, Space: 57, CapsLock: 58, F1: 59, F2: 60, F3: 61, F4: 62, F5: 63, F6: 64, F7: 65, F8: 66,
F9: 67, F10: 68, NumLock: 69, ScrollLock: 70, Numpad7: 71, Numpad8: 72, Numpad9: 73, NumpadSubtract: 74, Numpad4: 75,
Numpad5: 76, Numpad6: 77, NumpadAdd: 78, Numpad1: 79, Numpad2: 80, Numpad3: 81, Numpad0: 82, NumpadDecimal: 83,
IntlBackslash: 86, F11: 87, F12: 88, IntlRo: 89, NumpadEnter: 96, ControlRight: 97, NumpadDivide: 98, PrintScreen: 99,
AltRight: 100, Home: 102, ArrowUp: 103, PageUp: 104, ArrowLeft: 105, ArrowRight: 106, End: 107, ArrowDown: 108,
PageDown: 109, Insert: 110, Delete: 111, NumpadEqual: 117, Pause: 119, NumpadComma: 121, IntlYen: 124, MetaLeft: 125,
MetaRight: 126, ContextMenu: 127 };
let ws = null, W = 0, H = 0, scale = 1, ox = 0, oy = 0, queue = Promise.resolve(), pend = null, mx = -1, my = -1, lastSent = '';
const held = new Set();
function fit() {
if (!W) return;
const sw = innerWidth, sh = innerHeight;
scale = Math.min(sw / W, sh / H);
if (Math.abs(scale - 1) < 0.02) scale = 1;
for (const el of [stage, cv, vid]) { el.style.width = Math.round(W * scale) + 'px'; el.style.height = Math.round(H * scale) + 'px'; }
const r = cv.getBoundingClientRect();
ox = r.left; oy = r.top;
}
addEventListener('resize', fit);
// The session takes the window's size (if the monitor is showing it, the monitor wins), and the video
// this screen's refresh rate (60, 120, 144 Hz…), measured with animation frames once the page shows.
let resizeTimer = 0, screenHz = 0;
function sendSize() {
const m = { t: 'resize', w: Math.round(innerWidth) & ~1, h: Math.round(innerHeight) & ~1 };
if (screenHz) m.hz = screenHz;
send(m);
}
addEventListener('resize', () => {
clearTimeout(resizeTimer);
resizeTimer = setTimeout(sendSize, 400);
});
function measureHz() {
let n = 0, t0 = 0;
const step = (t) => {
if (!t0) t0 = t;
if (t - t0 < 1000) { n++; requestAnimationFrame(step); return; }
const raw = n * 1000 / (t - t0);
if (document.hidden || raw < 24) return; // a hidden tab is throttled: no measure
const hz = [30, 48, 50, 60, 72, 75, 90, 100, 120, 144, 165, 180, 240].reduce((a, b) => (Math.abs(b - raw) < Math.abs(a - raw) ? b : a));
if (hz !== screenHz) { screenHz = hz; sendSize(); setMode(); }
};
requestAnimationFrame(step);
}
document.addEventListener('visibilitychange', () => { if (!document.hidden) measureHz(); });
function send(o) { if (ws && ws.readyState === 1) ws.send(JSON.stringify(o)); }
// Input goes over the WebRTC data channel when it's open (lower latency), else over the WebSocket.
function sendIn(o) {
const j = JSON.stringify(o);
if (dcIn && dcIn.readyState === 'open' && j.length < 200000) dcIn.send(j); else send(o);
}
// ---- messages: a small "reconnecting" note, or a full card (error, unsupported browser) ----
function note(on) { $('again-text').textContent = T.reconn; $('again-note').style.display = on ? 'block' : 'none'; }
function el(tag, text, cls) { const e = document.createElement(tag); if (text) e.textContent = text; if (cls) e.className = cls; return e; }
function card(build) {
const c = $('card');
c.textContent = '';
build(c);
$('msg').style.display = 'grid';
}
function hideCard() { $('msg').style.display = 'none'; }
function waiting(text) { card((c) => { const p = el('p'); p.append(el('span', '', 'spin'), text); c.append(p); }); }
const fill = (s) => s.replace(/\{port\}/g, PORT);
// What this browser has: WebRTC, data channels and a video codec the computer sends (H.264 or VP8).
function support() {
const rtc = typeof RTCPeerConnection === 'function' && typeof RTCDataChannel === 'function';
let codec = rtc;
try {
const caps = typeof RTCRtpReceiver === 'function' && RTCRtpReceiver.getCapabilities && RTCRtpReceiver.getCapabilities('video');
if (caps && Array.isArray(caps.codecs)) codec = caps.codecs.some((c) => /^video\/(h264|vp8)$/i.test(c.mimeType));
} catch (e) {}
return { rtc, codec, secure: window.isSecureContext !== false };
}
function unsupported(s) {
rd.state = 'unsupported';
card((c) => {
c.append(el('h1', T.unsupTitle), el('p', T.unsupText));
const ul = el('ul');
for (const [ok, text] of [[s.rtc, T.reqRtc], [s.codec, T.reqCodec], [s.secure, T.reqSecure]]) ul.append(el('li', (ok ? '✓ ' : '✗ ') + text, ok ? '' : 'no'));
c.append(ul, el('div', T.unsupWhat, 'what'));
const b = el('div', '', 'btns'), so = el('button', T.signout, 'plain');
so.onclick = signOut;
b.append(so);
c.append(b);
});
}
function failure(why, detail) {
rd.state = 'failed';
rd.why = why;
note(false);
const key = T[why] ? why : 'server';
card((c) => {
c.append(el('h1', T.failTitle));
c.append(el('p', `${T.why}: ${fill(T[key])}`));
c.append(el('div', `${T.what}: ${fill(T[key + 'What'])}`, 'what'));
if (detail) c.append(el('div', `${T.details}: ${detail}`, 'det'));
const b = el('div', '', 'btns'), so = el('button', T.signout, 'plain'), again = el('button', T.retry);
so.onclick = signOut;
again.onclick = () => { hideCard(); retryAll(); };
b.append(so, again);
c.append(b);
setTimeout(() => again.focus(), 0);
});
}
// ---- the WebRTC peer: H.264/VP8 + Opus from the session's encoder; input and the lossless refresh
// of still areas over data channels ----
let pc = null, dcIn = null, vmode = false, codec = '', iceServers = [], offering = false, offersSent = 0, answersGot = 0, peerNo = 0;
let playTimer = 0, discTimer = 0, restartTimer = 0, restartTries = 0, peerFails = 0, everPlayed = false, serverWhy = '';
// The top bar: codec and path, frames a second shown / what the computer encodes, this screen's
// refresh rate, and how the computer makes the video (GPU or CPU composition, encoder in hardware or software)
let vinfo = null, shownFps = 0;
function setMode() {
if (!vmode) { $('mode').textContent = ''; $('mode').title = ''; return; }
const parts = [T.video, codec.toUpperCase() + (vinfo ? ' ' + (vinfo.hw ? T.hwEnc : T.swEnc) : '')];
if (rd.path) parts.push(rd.path.toUpperCase());
parts.push(vinfo ? `${shownFps}/${vinfo.fps} fps` : `${shownFps} fps`); // shown by this browser / encoded
if (screenHz) parts.push(`${screenHz} Hz`);
if (vinfo) parts.push(vinfo.gpu ? 'GPU' : 'CPU');
$('mode').textContent = parts.join(' · ');
$('mode').title = vinfo ? T.vinfoTip(vinfo.gpu ? 'GPU' : 'CPU', vinfo.hw ? T.hwEnc : T.swEnc, vinfo.ms) : '';
}
setInterval(() => {
if (!vmode || !pc) return;
pc.getStats().then((st) => {
st.forEach((s) => { if (s.type === 'inbound-rtp' && s.kind === 'video') shownFps = Math.round(s.framesPerSecond || 0); });
setMode();
}).catch(() => {});
}, 1000);
function clearTimers() { clearTimeout(playTimer); clearTimeout(discTimer); clearTimeout(restartTimer); }
function closePeer() {
clearTimers();
if (pc) { pc.onconnectionstatechange = pc.oniceconnectionstatechange = pc.onnegotiationneeded = pc.onicecandidate = pc.ontrack = null; try { pc.close(); } catch (e) {} }
pc = null; dcIn = null; offering = false; offersSent = answersGot = 0;
const was = vmode;
vmode = false;
vid.style.visibility = 'hidden'; vid.srcObject = null; $('snd').hidden = true;
if (was) queue = queue.then(() => ctx.clearRect(0, 0, W, H));
setMode();
}
function enterVideo() {
if (vmode || !pc) return;
clearTimeout(playTimer);
vmode = true;
everPlayed = true;
peerFails = 0;
rd.why = '';
restartTries = 0;
rd.state = 'playing';
hideCard();
note(false);
queue = queue.then(() => ctx.clearRect(0, 0, W, H));
vid.style.visibility = 'visible';
$('snd').hidden = false;
send({ t: 'vmode', on: 1 });
setMode();
}
const gathered = (p) => new Promise((ok) => {
if (p.iceGatheringState === 'complete') return ok();
const t = setTimeout(ok, 1500);
p.addEventListener('icegatheringstatechange', () => { if (p.iceGatheringState === 'complete') { clearTimeout(t); ok(); } });
});
// the browser's offer (the first one, or an ICE restart's) over the authenticated WebSocket
function offer(restart) {
if (!pc || offering) return;
const p = pc;
offering = true;
p.createOffer(restart ? { iceRestart: true } : {}).then((o) => p.setLocalDescription(o)).then(() => gathered(p))
.then(() => { if (pc === p) { offersSent++; send({ t: 'rtc', sdp: p.localDescription.sdp, p: peerNo }); } })
.catch(() => { offering = false; if (pc === p) peerFailed('offer', 'createOffer'); });
}
function startPeer() {
closePeer();
rd.peers++;
rd.state = 'connecting';
serverWhy = '';
try {
pc = new RTCPeerConnection({ iceServers: iceServers.map((u) => ({ urls: u })), bundlePolicy: 'max-bundle', rtcpMuxPolicy: 'require' });
} catch (e) { pc = null; unsupported(support()); return; }
pc.addTransceiver('video', { direction: 'recvonly' });
pc.addTransceiver('audio', { direction: 'recvonly' });
dcIn = pc.createDataChannel('input', { ordered: true });
const tiles = pc.createDataChannel('tiles', { ordered: true });
tiles.binaryType = 'arraybuffer';
tiles.onmessage = (e) => onTile(new Uint8Array(e.data));
pc.ontrack = (e) => {
// a desktop wants the newest frame now, not a smooth buffer
try { e.receiver.jitterBufferTarget = 0; } catch (x) {}
try { e.receiver.playoutDelayHint = 0; } catch (x) {}
const ms = e.streams[0] || new MediaStream([e.track]);
if (vid.srcObject !== ms) vid.srcObject = ms;
vid.play().catch(() => {});
};
pc.onicecandidate = (e) => { if (e.candidate && e.candidate.candidate && !offering) send({ t: 'ice', c: e.candidate.candidate, p: peerNo }); };
pc.oniceconnectionstatechange = () => iceState(pc && pc.iceConnectionState);
offer(false);
// no picture within 15 s: say why (the server's reason if it gave one, else what this side saw)
const p = pc;
playTimer = setTimeout(() => { if (pc === p && !vmode) diagnose(p).then((d) => peerFailed(d.why, d.text)); }, 15000);
}
// ICE lost its path: restart it (new credentials, the same encrypted channel), then a new peer
function iceState(st) {
if (!pc) return;
if (st === 'connected' || st === 'completed') {
clearTimeout(discTimer); clearTimeout(restartTimer);
restartTries = 0;
offering = false;
if (vmode) rd.state = 'playing';
note(false);
pathKind();
return;
}
if (!vmode) return; // still connecting: the play timer decides
if (st === 'disconnected') {
note(true);
clearTimeout(discTimer);
discTimer = setTimeout(() => restartIce(), 2000);
} else if (st === 'failed') { note(true); restartIce(); }
}
function restartIce() {
if (!pc) return;
clearTimeout(restartTimer);
// the WebSocket can't deliver our last offer yet (its path is down too): wait, don't pile up offers
if (offering || (ws && ws.bufferedAmount > 0)) { restartTimer = setTimeout(restartIce, 1000); return; }
if (restartTries >= 6) { renewPeer('lost'); return; } // about 40 s of restarts: a new peer
restartTries++;
rd.restarts++;
rd.state = 'restarting';
try { if (pc.restartIce) pc.restartIce(); } catch (e) {}
offer(true);
restartTimer = setTimeout(() => {
if (!pc) return;
const st = pc.iceConnectionState;
if (st !== 'connected' && st !== 'completed') { offering = false; restartIce(); }
}, Math.min(8000, 2000 * restartTries));
}
// this peer is done: ask the bridge for a new one ({"t":"vmode","on":0}); its "ready" starts it
function renewPeer(why) {
serverWhy = why;
closePeer();
note(true);
rd.state = 'renewing';
if (ws && ws.readyState === 1) send({ t: 'vmode', on: 0 });
else connect();
}
// A peer failed before (or after) playing. Twice in a row without a picture: the card, with Retry.
function peerFailed(why, detail) {
peerFails++;
if (why === 'codec') { closePeer(); unsupported({ rtc: true, codec: false, secure: window.isSecureContext !== false }); return; }
if (why === 'noroute' && everPlayed) why = 'lost'; // it worked before: the network went away
if (peerFails >= 2) { closePeer(); failure(why, detail); if (ws && ws.readyState === 1) send({ t: 'vmode', on: 0 }); return; }
renewPeer(why);
}
// What went wrong, from the browser's side: the ICE state and the candidate pairs it tried.
function diagnose(p) {
const base = { why: serverWhy || 'noroute', text: '' };
if (!p || !p.getStats) return Promise.resolve(base);
return p.getStats().then((stats) => {
let pairs = 0, ok = 0, udp = 0, tcp = 0, gotFrames = 0;
stats.forEach((s) => {
if (s.type === 'candidate-pair') { pairs++; if (s.state === 'succeeded') ok++; }
if (s.type === 'remote-candidate') { if (s.protocol === 'tcp') tcp++; else udp++; }
if (s.type === 'inbound-rtp' && s.kind === 'video') gotFrames = s.framesDecoded || 0;
});
const ice = p.iceConnectionState, dtls = p.connectionState;
let why = serverWhy;
if (!why) why = answersGot === 0 ? 'offer' : ok === 0 ? 'noroute' : dtls !== 'connected' ? 'dtls' : 'media';
if (why === 'noroute' && ok > 0) why = 'dtls';
return { why, text: `ICE ${ice}, ${dtls}; ${pairs} candidate pairs (${ok} succeeded), the computer offered ${udp} UDP and ${tcp} TCP addresses still listed; ${gotFrames} frames decoded${serverWhy ? '; the computer said: ' + serverWhy : ''}` };
}).catch(() => base);
}
// which path the media takes (shown in the top bar): UDP, TCP or a relay
function pathKind() {
if (!pc || !pc.getStats) return;
pc.getStats().then((stats) => {
let sel = '';
stats.forEach((s) => { if (s.type === 'transport' && s.selectedCandidatePairId) sel = s.selectedCandidatePairId; });
const pair = sel && stats.get(sel);
const rc = pair && stats.get(pair.remoteCandidateId);
if (rc) { rd.path = rc.candidateType === 'relay' ? 'relay' : rc.protocol || ''; setMode(); }
}).catch(() => {});
}
const onFrame = () => { if (vid.videoWidth > 0) enterVideo(); else vid.requestVideoFrameCallback?.(onFrame); };
vid.addEventListener('playing', () => { if (vid.videoWidth > 0) enterVideo(); });
vid.addEventListener('loadeddata', onFrame);
// [1][x,y,w,h u16][png]: a lossless tile · [2][x,y,w,h…]: those areas changed (show the video there) · [3]: done
function onTile(d) {
if (!vmode) return;
if (d[0] === 1 && d.length > 9) {
const x = d[1] << 8 | d[2], y = d[3] << 8 | d[4], w = d[5] << 8 | d[6], h = d[7] << 8 | d[8];
const p = createImageBitmap(new Blob([d.subarray(9)], { type: 'image/png' }));
queue = queue.then(() => p).then((bmp) => { if (vmode) ctx.drawImage(bmp, x, y, w, h); bmp.close(); }, () => {});
} else if (d[0] === 2) {
const r = [];
for (let i = 1; i + 8 <= d.length; i += 8) r.push([d[i] << 8 | d[i + 1], d[i + 2] << 8 | d[i + 3], d[i + 4] << 8 | d[i + 5], d[i + 6] << 8 | d[i + 7]]);
queue = queue.then(() => { for (const [x, y, w, h] of r) ctx.clearRect(x, y, w, h); });
}
}
function setSound(on) {
vid.muted = !on;
if (on) vid.play().catch(() => {});
$('snd').textContent = vid.muted ? '🔇' : '🔊';
$('snd').title = vid.muted ? T.sndOn : T.sndOff;
}
// browsers only play sound after a gesture: the first click or key in the session turns it on, unless
// the viewer already chose with the button (hidden in the top bar)
let soundChosen = false;
$('snd').onclick = () => { soundChosen = true; setSound(vid.muted); };
const soundOnGesture = () => { if (!soundChosen && vid.muted && !$('snd').hidden) { soundChosen = true; setSound(true); } };
$('c').addEventListener('pointerdown', soundOnGesture);
$('c').addEventListener('keydown', soundOnGesture);
// ---- the WebSocket: sign-in, signaling, cursor, clipboard. Reconnects with backoff, without a new
// sign-in while the cookie lasts; if the cookie is gone, /desk sends the browser to the sign-in page ----
let wsTries = 0, wsTimer = 0, helloSeen = false, wantedClose = false;
function connect() {
clearTimeout(wsTimer);
if (ws) { ws.onclose = null; try { ws.close(); } catch (e) {} ws = null; }
closePeer();
const w = Math.round(innerWidth), h = Math.round(innerHeight);
helloSeen = false;
ws = new WebSocket(`wss://${location.host}/ws?w=${w}&h=${h}&v=1`);
ws.binaryType = 'arraybuffer';
ws.onopen = () => { rd.wsOpens++; sendSize(); measureHz(); }; // an existing session takes this size
ws.onmessage = (e) => (typeof e.data === 'string' ? onText(JSON.parse(e.data)) : onBin(new Uint8Array(e.data)));
ws.onclose = () => {
ws = null;
closePeer();
if (wantedClose) return;
wsTries++;
if (!helloSeen && wsTries >= 2) {
// refused twice before the hello: is the sign-in still valid? (a redirect means it isn't)
fetch('/desk', { redirect: 'manual', cache: 'no-store' }).then((r) => {
if (r.type === 'opaqueredirect' || r.status === 303) location.replace('/');
else later();
}, later);
} else later();
};
}
function later() {
const d = Math.min(30000, 1000 * 2 ** Math.min(wsTries, 5));
if (wsTries >= 3) failure('wsdown', `WebSocket closed ${wsTries} times; next try in ${Math.round(d / 1000)} s`);
else note(true);
rd.state = 'offline';
wsTimer = setTimeout(() => { if (rd.state === 'offline') connect(); }, d);
}
function retryAll() {
peerFails = 0; restartTries = 0; wsTries = 0;
if (ws && ws.readyState === 1 && iceServers.length) { waiting(T.conn); renewPeer(''); }
else { waiting(T.conn); connect(); }
}
function onText(m) {
if (m.t === 'size') { W = m.w; H = m.h; cv.width = W; cv.height = H; ctx.clearRect(0, 0, W, H); fit(); }
else if (m.t === 'vinfo') { vinfo = { hw: !!m.hw, gpu: !!m.gpu, fps: m.fps | 0, ms: Number(m.ms) || 0 }; setMode(); }
else if (m.t === 'hello') {
helloSeen = true;
wsTries = 0;
$('who').textContent = `${m.user}@${location.hostname}`;
if (!m.rtc || !Array.isArray(m.ice)) { failure('server', 'the computer has no WebRTC peer for this connection'); return; }
iceServers = m.ice;
peerNo = m.p || 1;
startPeer();
} else if (m.t === 'rtc') {
if (m.ready && m.p) peerNo = m.p;
if (m.sdp && m.p && m.p !== peerNo) return; // the answer of a peer that's already gone
if (m.fail) {
// the bridge closed this peer and says why (RTC_WHY_* in rtc.h, or codec, offer, restart, or
// browser: the page asked for it); a new peer comes with "ready" (or in a later message)
if (m.ready && Array.isArray(m.ice)) iceServers = m.ice;
const mine = m.fail === 'browser' || m.fail === 'restart';
if (!mine) {
const was = pc;
diagnose(was).then((d) => {
closePeer();
if (m.fail === 'codec') { peerFailed('codec'); return; }
serverWhy = m.fail;
peerFails++;
let why = m.fail === 'noroute' && everPlayed ? 'lost' : m.fail;
if (peerFails >= 2) { failure(why, `the computer said: ${m.fail}; ${d.text}`); return; }
note(true);
if (m.ready) setTimeout(() => { if (!pc && rd.state !== 'failed') startPeer(); }, 1000);
});
return;
}
if (m.why2 === 'server') { closePeer(); failure('server', 'the computer could not create a new peer'); return; }
if (m.ready && rd.state !== 'failed') { closePeer(); startPeer(); }
return;
}
if (m.ready && Array.isArray(m.ice)) { // a peer that had to wait (the 2 s limit) is there now
iceServers = m.ice;
if (!pc && rd.state !== 'failed') startPeer();
return;
}
if (m.sdp && pc) {
const p = pc;
if (++answersGot < offersSent) return; // an answer to an older offer of ours: the newest one follows
if (!m.restart) codec = m.codec || '';
p.setRemoteDescription({ type: 'answer', sdp: m.sdp }).then(() => { offering = false; }, () => { offering = false; if (pc === p) peerFailed('offer', 'setRemoteDescription'); });
}
}
else if (m.t === 'pong') { $('lat').textContent = `${Math.max(0, Math.round(performance.now() - m.ts))} ms`; if (vmode) pathKind(); }
else if (m.t === 'cur') {
// cursor moved by someone else (the monitor or another connection): drawn on top
const rc = $('rcur');
if (m.m === 2 || (Math.abs(m.x - mx) <= 2 && Math.abs(m.y - my) <= 2)) rc.style.display = 'none';
else { rc.style.display = 'block'; rc.style.left = (ox + m.x * scale) + 'px'; rc.style.top = (oy + m.y * scale) + 'px'; }
if (m.m === 2) cv.style.cursor = 'none';
else if (m.m === 0) cv.style.cursor = 'default';
} else if (m.t === 'clip') {
if (navigator.clipboard && document.hasFocus()) navigator.clipboard.writeText(m.text).catch(() => {});
lastSent = m.text;
} else if (m.t === 'bye' && m.lock) { wantedClose = true; location.href = '/?e=3'; } // the session got locked: sign in again
else if (m.t === 'bye') {
wantedClose = true;
closePeer();
card((c) => { c.append(el('h1', T.bye)); const b = el('div', '', 'btns'), a = el('button', T.retry); a.onclick = () => { wantedClose = false; hideCard(); retryAll(); }; b.append(a); c.append(b); });
}
}
function onBin(d) {
if (d[0] === 2) { // an app's cursor image
const w = d[1] << 8 | d[2], hx = d[5] << 8 | d[6], hy = d[7] << 8 | d[8];
const url = URL.createObjectURL(new Blob([d.subarray(9)], { type: 'image/png' }));
const k = scale === 1 ? 1 : scale;
cv.style.cursor = w <= 128 ? `url(${url}) ${Math.round(hx * k)} ${Math.round(hy * k)}, default` : 'default';
}
}
function pos(e) {
const x = Math.round((e.clientX - ox) / scale), y = Math.round((e.clientY - oy) / scale);
return [Math.max(0, Math.min(W - 1, x)), Math.max(0, Math.min(H - 1, y))];
}
function flushMove() { if (pend) { sendIn({ t: 'm', x: pend[0], y: pend[1] }); pend = null; } }
cv.addEventListener('pointermove', (e) => {
[mx, my] = pos(e);
if (!pend) requestAnimationFrame(flushMove);
pend = [mx, my];
});
cv.addEventListener('pointerdown', (e) => {
cv.focus(); cv.setPointerCapture(e.pointerId);
pend = pos(e); flushMove();
if (e.button <= 2) sendIn({ t: 'b', b: e.button, d: 1 });
e.preventDefault();
});
cv.addEventListener('pointerup', (e) => { pend = pos(e); flushMove(); if (e.button <= 2) sendIn({ t: 'b', b: e.button, d: 0 }); });
cv.addEventListener('contextmenu', (e) => e.preventDefault());
// Wheel: a mouse sends steps ('w'); a trackpad, pixels with a phase ('s': 1 begins, 2 continues, 3
// ends) and pinch arrives as a wheel with ctrlKey (Chrome, Firefox) or gesturechange (WebKit browsers)
// ('pz': scale relative to the start). Gestures end after 150 ms without events.
let scrollOn = false, scrollT = 0, pinchOn = false, pinchT = 0, pinchScale = 1, pinchRot = 0;
function pinch(scale, rot) {
if (!pinchOn) { pinchOn = true; pinchScale = 1; pinchRot = 0; sendIn({ t: 'pz', p: 1, s: 65536, r: 0 }); }
pinchScale = Math.max(0.1, Math.min(10, scale)); pinchRot = rot;
sendIn({ t: 'pz', p: 2, s: Math.round(pinchScale * 65536), r: Math.round(pinchRot * 256) });
clearTimeout(pinchT);
pinchT = setTimeout(() => { pinchOn = false; sendIn({ t: 'pz', p: 3, s: Math.round(pinchScale * 65536), r: Math.round(pinchRot * 256) }); }, 150);
}
cv.addEventListener('wheel', (e) => {
e.preventDefault();
[mx, my] = pos(e); pend = [mx, my]; flushMove(); // the wheel goes where the pointer is now
const k = e.deltaMode === 1 ? 16 : e.deltaMode === 2 ? H : 1; // to pixels
if (e.ctrlKey) { pinch(pinchScale * Math.max(0.8, Math.min(1.25, Math.exp(-e.deltaY * k / 100))), pinchRot); return; }
const wheelLike = e.deltaMode !== 0 || (!e.deltaX && Number.isInteger(e.deltaY) && Math.abs(e.deltaY) >= 50 && !scrollOn);
if (wheelLike) {
const steps = e.deltaMode === 1 ? -Math.sign(e.deltaY) * Math.max(1, Math.round(Math.abs(e.deltaY) / 3)) : -Math.sign(e.deltaY) * Math.max(1, Math.round(Math.abs(e.deltaY) / 100));
if (steps) sendIn({ t: 'w', d: steps });
return;
}
if (!scrollOn) { scrollOn = true; sendIn({ t: 's', p: 1, x: 0, y: 0 }); }
sendIn({ t: 's', p: 2, x: Math.round(e.deltaX * k / scale * 256), y: Math.round(e.deltaY * k / scale * 256) });
clearTimeout(scrollT);
scrollT = setTimeout(() => { scrollOn = false; sendIn({ t: 's', p: 3, x: 0, y: 0 }); }, 150);
}, { passive: false });
cv.addEventListener('gesturestart', (e) => e.preventDefault());
cv.addEventListener('gesturechange', (e) => { e.preventDefault(); pinch(e.scale, e.rotation || 0); });
cv.addEventListener('gestureend', (e) => e.preventDefault());
function key(e, down) {
const c = K[e.code];
if (!c) return;
// Ctrl+V: let the browser fire "paste" (the local clipboard goes first)
if (down && e.code === 'KeyV' && (e.ctrlKey || e.metaKey)) return;
e.preventDefault();
if (down) held.add(c); else held.delete(c);
sendIn({ t: 'k', c, d: down ? 1 : 0 });
}
cv.addEventListener('keydown', (e) => key(e, true));
cv.addEventListener('keyup', (e) => key(e, false));
cv.addEventListener('blur', () => { for (const c of held) sendIn({ t: 'k', c, d: 0 }); held.clear(); });
document.addEventListener('paste', (e) => {
const text = e.clipboardData && e.clipboardData.getData('text/plain');
if (text && text !== lastSent) { sendIn({ t: 'clip', text }); lastSent = text; }
sendIn({ t: 'k', c: 47, d: 1 }); sendIn({ t: 'k', c: 47, d: 0 });
e.preventDefault();
});
setInterval(() => send({ t: 'ping', ts: Math.round(performance.now()) }), 2000);
let hideT = 0;
addEventListener('mousemove', (e) => {
if (e.clientY < 8) { $('bar').classList.add('show'); clearTimeout(hideT); hideT = setTimeout(() => $('bar').classList.remove('show'), 2500); }
});
$('fs').onclick = () => (document.fullscreenElement ? document.exitFullscreen() : document.documentElement.requestFullscreen()).then(() => setTimeout(fit, 200));
// signing out is a POST from this page (the server checks its Origin), never a link another site could open
function signOut() {
wantedClose = true;
if (ws) ws.close();
closePeer();
const f = document.createElement('form');
f.method = 'post'; f.action = '/logout';
document.body.appendChild(f); f.submit();
}
$('out').onclick = signOut;
$('bar').classList.add('show'); hideT = setTimeout(() => $('bar').classList.remove('show'), 3000);
// 📌 keeps the bar shown (remembered in this browser only)
function setPin(on) {
$('bar').classList.toggle('pinned', on);
$('pin').classList.toggle('on', on);
$('pin').title = on ? T.pinOff : T.pinOn;
try { localStorage.setItem('lordos.rd.pin', on ? '1' : ''); } catch (e) {}
}
let pinned = false;
try { pinned = localStorage.getItem('lordos.rd.pin') === '1'; } catch (e) {}
setPin(pinned);
$('pin').onclick = () => { pinned = !pinned; setPin(pinned); };
const sup = support();
if (!sup.rtc || !sup.codec || !sup.secure) unsupported(sup);
else { waiting(T.conn); connect(); cv.focus(); }
</script>
</body>
</html>