datarhei-dragonfork-core/test/whep-player.html

355 lines
11 KiB
HTML
Raw Permalink Normal View History

ci+test: forgejo workflow, browser WHEP player, TESTING.md (M4 part 1) Three artifacts that close out the easier half of the M4 milestone: 1. .forgejo/workflows/test.yml — CI on every push and PR. Three jobs: - lint-and-vet: go vet + go build (~30s) - test: go test -race -short ./... + a no-race coverage pass that uploads coverage.out as an artifact - webrtc-smoke: TestIntegration_FiveViewerFanout and the rest of the WebRTC subsystem tests in isolation, so a failure on the egress path stays readable in the log. Pinned to Go 1.24 to match go.mod. The forge has a forgejo-runner sibling container; this YAML uses GitHub Actions syntax which Forgejo Actions accepts unchanged. 2. test/whep-player.html — self-contained browser WHEP subscriber for manual smoke testing. RTCPeerConnection (recvonly V+A) + fetch() POST/DELETE/PATCH against /api/v3/whep/:id, ICE/PC state pills, inbound-bitrate sampling at 1 Hz, codec hint pulled from the answer SDP, JWT token field, ?url=&token= shareable query string. No external deps; works from file:// or any static host. 3. test/TESTING.md — short doc that ties together the in-process race tests, the browser player, and the existing Pion CLI helper at test/whep-client/. Notes the latency p95 gate as a follow-up. Latency gate (FFmpeg drawtext frame counter + decode-side pixel sampling, p95 < 300ms RTMP / < 200ms SRT) is queued for a separate PR — it's a several-hundred-line addition in its own right and shouldn't block CI from landing. Co-Authored-By: Claude Opus 4.7 <noreply@anthropic.com>
2026-05-03 08:14:25 -04:00
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>Dragon Fork — WHEP Player</title>
<meta name="viewport" content="width=device-width, initial-scale=1">
<style>
:root {
color-scheme: light dark;
--fg: #e7e7ea;
--bg: #0d0e12;
--accent: #ff6633;
--muted: #8b8e98;
--good: #5dd29c;
--warn: #ffb45e;
--bad: #ff6470;
--panel: #1a1c22;
}
* { box-sizing: border-box; }
body {
margin: 0;
font: 14px/1.5 -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, sans-serif;
background: var(--bg);
color: var(--fg);
min-height: 100vh;
display: flex;
flex-direction: column;
}
header {
padding: 1.25rem 1.5rem;
border-bottom: 1px solid #232530;
display: flex;
align-items: baseline;
gap: 0.75rem;
}
header h1 {
margin: 0;
font-size: 1.05rem;
letter-spacing: 0.02em;
}
header h1 .accent { color: var(--accent); }
header .subtitle { color: var(--muted); font-size: 0.85rem; }
main {
display: grid;
grid-template-columns: 1fr;
gap: 1rem;
padding: 1.5rem;
max-width: 1200px;
width: 100%;
margin: 0 auto;
flex: 1;
}
@media (min-width: 900px) {
main {
grid-template-columns: 360px 1fr;
align-items: start;
}
}
.panel {
background: var(--panel);
border-radius: 10px;
padding: 1.25rem;
}
label {
display: block;
margin-top: 0.75rem;
color: var(--muted);
font-size: 0.78rem;
text-transform: uppercase;
letter-spacing: 0.06em;
}
input[type=text] {
width: 100%;
padding: 0.55rem 0.7rem;
margin-top: 0.25rem;
background: #0d0e12;
border: 1px solid #2a2c36;
border-radius: 6px;
color: var(--fg);
font: inherit;
}
input[type=text]:focus { border-color: var(--accent); outline: none; }
.actions {
display: flex;
gap: 0.5rem;
margin-top: 1.25rem;
}
button {
flex: 1;
padding: 0.7rem 1rem;
border: none;
border-radius: 6px;
background: var(--accent);
color: #000;
font-weight: 600;
cursor: pointer;
}
button:disabled { opacity: 0.4; cursor: not-allowed; }
button.secondary { background: #2a2c36; color: var(--fg); }
video {
width: 100%;
background: #000;
border-radius: 10px;
aspect-ratio: 16 / 9;
}
.stats {
display: grid;
grid-template-columns: max-content 1fr;
gap: 0.4rem 1rem;
margin-top: 1rem;
font-size: 0.85rem;
}
.stats .label { color: var(--muted); }
.stats .value { font-variant-numeric: tabular-nums; }
.pill {
display: inline-block;
padding: 0.1rem 0.55rem;
border-radius: 999px;
font-size: 0.75rem;
background: #2a2c36;
}
.pill.good { background: rgba(93,210,156,0.18); color: var(--good); }
.pill.warn { background: rgba(255,180,94,0.18); color: var(--warn); }
.pill.bad { background: rgba(255,100,112,0.20); color: var(--bad); }
.log {
margin-top: 1rem;
max-height: 220px;
overflow-y: auto;
background: #0d0e12;
padding: 0.6rem 0.8rem;
border-radius: 6px;
font-family: ui-monospace, SFMono-Regular, Menlo, Consolas, monospace;
font-size: 0.78rem;
line-height: 1.4;
white-space: pre-wrap;
word-break: break-word;
}
.log .ts { color: var(--muted); }
</style>
</head>
<body>
<header>
<h1>Dragon Fork <span class="accent">WHEP</span></h1>
<span class="subtitle">manual smoke test for the WebRTC egress path</span>
</header>
<main>
<section class="panel">
<label for="whep-url">WHEP endpoint</label>
<input id="whep-url" type="text" placeholder="http://10.0.0.25:8090/api/v3/whep/myStream"
value="">
<label for="bearer">JWT bearer token</label>
<input id="bearer" type="text" placeholder="eyJhbGciOi…">
<div class="actions">
<button id="btn-play">Subscribe</button>
<button id="btn-stop" class="secondary" disabled>Disconnect</button>
</div>
<div class="stats">
<span class="label">ICE</span> <span id="stat-ice" class="value pill">idle</span>
<span class="label">Connection</span> <span id="stat-conn" class="value pill">idle</span>
<span class="label">Resource</span> <span id="stat-res" class="value"></span>
<span class="label">Video codec</span> <span id="stat-vcodec" class="value"></span>
<span class="label">Audio codec</span> <span id="stat-acodec" class="value"></span>
<span class="label">Inbound bitrate</span><span id="stat-bitrate" class="value"></span>
</div>
<div id="log" class="log" aria-live="polite"></div>
</section>
<section class="panel" style="padding:0;background:#000;">
<video id="video" controls autoplay playsinline muted></video>
</section>
</main>
<script>
// --- tiny state -------------------------------------------------
const $ = (id) => document.getElementById(id);
const log = (line, level='info') => {
const ts = new Date().toLocaleTimeString();
const div = document.createElement('div');
div.innerHTML = `<span class="ts">${ts}</span> <span class="lvl-${level}">${line}</span>`;
$('log').prepend(div);
};
const setPill = (el, text, klass) => { el.textContent = text; el.className = 'value pill ' + klass; };
let pc = null;
let resourceURL = null; // absolute or path; whichever the server returned
let bitrateTimer = null;
// --- subscribe / disconnect -------------------------------------
$('btn-play').addEventListener('click', subscribe);
$('btn-stop').addEventListener('click', disconnect);
// Pre-populate WHEP endpoint from query string for shareable URLs
// (e.g. file:///.../whep-player.html?url=http://.../whep/foo&token=…).
(function bootstrap() {
const q = new URLSearchParams(location.search);
if (q.get('url')) $('whep-url').value = q.get('url');
if (q.get('token')) $('bearer').value = q.get('token');
})();
async function subscribe() {
if (pc) { log('already connected; disconnect first', 'warn'); return; }
const url = $('whep-url').value.trim();
const token = $('bearer').value.trim();
if (!url) { log('WHEP URL is required', 'bad'); return; }
$('btn-play').disabled = true;
$('btn-stop').disabled = false;
setPill($('stat-ice'), 'gathering', 'warn');
setPill($('stat-conn'), 'connecting', 'warn');
pc = new RTCPeerConnection({
// No ICE servers: production deploy advertises NAT1To1 host
// candidates, which work over the LAN. Add stun:/turn: here
// if you're testing across NAT.
iceServers: [],
});
pc.ontrack = (evt) => {
log(`ontrack: kind=${evt.track.kind}`, 'info');
// Both tracks share the same MediaStream; attach once.
if ($('video').srcObject !== evt.streams[0]) {
$('video').srcObject = evt.streams[0];
}
};
pc.oniceconnectionstatechange = () => {
const s = pc.iceConnectionState;
let klass = 'warn';
if (s === 'connected' || s === 'completed') klass = 'good';
else if (s === 'failed' || s === 'disconnected' || s === 'closed') klass = 'bad';
setPill($('stat-ice'), s, klass);
log(`ICE state: ${s}`);
};
pc.onconnectionstatechange = () => {
const s = pc.connectionState;
let klass = 'warn';
if (s === 'connected') klass = 'good';
else if (s === 'failed' || s === 'disconnected' || s === 'closed') klass = 'bad';
setPill($('stat-conn'), s, klass);
log(`PC state: ${s}`);
};
pc.addTransceiver('video', { direction: 'recvonly' });
pc.addTransceiver('audio', { direction: 'recvonly' });
try {
const offer = await pc.createOffer();
await pc.setLocalDescription(offer);
// Wait for ICE gathering to complete so the offer is non-trickle.
await new Promise((res) => {
if (pc.iceGatheringState === 'complete') return res();
pc.addEventListener('icegatheringstatechange', () => {
if (pc.iceGatheringState === 'complete') res();
});
});
const headers = { 'Content-Type': 'application/sdp' };
if (token) headers['Authorization'] = 'Bearer ' + token;
const resp = await fetch(url, {
method: 'POST',
headers,
body: pc.localDescription.sdp,
});
if (!resp.ok) {
const body = await resp.text();
throw new Error(`WHEP POST ${resp.status}: ${body || resp.statusText}`);
}
// Per WHEP spec: server returns SDP answer; Location is the resource.
const loc = resp.headers.get('Location');
if (loc) {
// Resolve relative Location against the WHEP URL.
try { resourceURL = new URL(loc, url).toString(); }
catch { resourceURL = loc; }
$('stat-res').textContent = resourceURL;
}
const answer = await resp.text();
await pc.setRemoteDescription({ type: 'answer', sdp: answer });
log(`subscribed (${resp.status})`, 'good');
// Pull codec info out of the SDP for a quick UI hint.
const codec = (kind, sdp) => {
const m = new RegExp(`m=${kind}[^\r\n]*[\r\n](?:[abc][^\r\n]*[\r\n]){0,30}?a=rtpmap:\\d+ ([^/\r\n]+)`).exec(sdp);
return m ? m[1] : '?';
};
$('stat-vcodec').textContent = codec('video', answer);
$('stat-acodec').textContent = codec('audio', answer);
bitrateTimer = setInterval(updateBitrate, 1000);
} catch (err) {
log(`error: ${err.message}`, 'bad');
await disconnect();
}
}
async function disconnect() {
if (bitrateTimer) { clearInterval(bitrateTimer); bitrateTimer = null; }
$('btn-play').disabled = false;
$('btn-stop').disabled = true;
// WHEP: best-effort DELETE on the resource URL the server gave us.
if (resourceURL) {
try {
const headers = {};
const token = $('bearer').value.trim();
if (token) headers['Authorization'] = 'Bearer ' + token;
const r = await fetch(resourceURL, { method: 'DELETE', headers });
log(`DELETE ${r.status}`, r.ok ? 'good' : 'warn');
} catch (e) {
log(`DELETE failed: ${e.message}`, 'warn');
}
resourceURL = null;
}
if (pc) { pc.close(); pc = null; }
$('video').srcObject = null;
setPill($('stat-ice'), 'idle', '');
setPill($('stat-conn'), 'idle', '');
$('stat-res').textContent = '—';
$('stat-vcodec').textContent = '—';
$('stat-acodec').textContent = '—';
$('stat-bitrate').textContent = '—';
}
// --- bitrate sampling -------------------------------------------
let lastBytes = null;
let lastTs = null;
async function updateBitrate() {
if (!pc || pc.connectionState !== 'connected') return;
const stats = await pc.getStats();
let bytes = 0;
stats.forEach((r) => {
if (r.type === 'inbound-rtp' && !r.isRemote) bytes += r.bytesReceived || 0;
});
const now = performance.now();
if (lastBytes !== null) {
const kbps = ((bytes - lastBytes) * 8) / ((now - lastTs) || 1);
$('stat-bitrate').textContent = kbps.toFixed(0) + ' kbps';
}
lastBytes = bytes;
lastTs = now;
}
</script>
</body>
</html>