This compatible update improves quality recovery after congestion and stream changes, and lets an approved Site become the App's startup page. It also aligns responsive controls and external brand assets while preserving the in-page mascot and illustrations. The existing media allocator, room graph and authorization owners remain in place. The scoped LiveKit demand-input patch is pinned and submitted upstream in livekit/livekit#5016; its removal condition is documented. No wire or storage version changes. ## Validation - Web type-check, unit tests and production build; Go core/native acceptance and website build. - Focused controlled recovery/relay/NAT evidence reused from this phase, plus final integrated lifecycle checks. - Independent media and UI reviews; corrected the ready App button's stale passive styling. - Repository hygiene, documentation links, responsive launcher/theme previews and package icon propagation. - Physical macOS/Linux capture and unmatched reporter cases remain documented; controlled tests do not establish a public connection success rate. ## Release notes ### 中文 这是一次兼容 2.x 的功能与维护更新,重点改善网络波动后的画质恢复,并让常用站点的 App 启动流程更方便。 - **更快恢复画质:** 修复部分 App 分享与服务器中转线路在网络恢复后仍长时间保持低码率的问题;调整 Windows 原生编码,减少短暂波动造成的分辨率下降,并加快恢复。 - **更稳定的中继播放:** 修复原生中继在分辨率变化、画面数据不完整和换源时的恢复处理,以及延迟关键帧请求被丢失的问题。 - **启动时打开常用站点:** 可以为已授权站点加星,下次启动 App 时直接打开它;仍可通过网页 App 按钮或终端地址返回启动页管理授权和选择模式。 - **简化连接设置:** NAT 穿透增强在能力可用时自动启用;高级用户可通过 `PIIK_STUN_URLS` 指定 App 公网邀请使用的 STUN 服务。 - **界面与图标打磨:** 修正窄屏房间工具栏、昵称编辑和浮层排版,精简启动页说明,统一官网与应用的语言、深浅色控件,并更新 App 图标与网站 favicon。页面内的 mascot 和插画保持原有风格。 - **补充连接排查指引:** 更清楚地区分公网邀请服务、站点访问与媒体连接问题。 本次更新不改变 2.x 通信协议或数据库格式。浏览器采集在部分网络波动后仍可能恢复较慢;此次修复不代表所有网络和设备上的画质问题均已消除。 ### English This compatible 2.x feature and maintenance update improves quality recovery after network disturbances and makes it easier to launch the App with your usual Site. - **Faster quality recovery:** Fixed cases where native App sharing or server-relayed media stayed at a low bitrate after bandwidth returned. Tuned Windows native encoding to reduce resolution drops during brief disturbances and recover sooner. - **More reliable relay playback:** Fixed native relay recovery across resolution changes, incomplete frames and source replacement, and preserved delayed keyframe requests until they can be fulfilled. - **Open your usual Site on startup:** Star an approved Site to open it when the App starts. The page's App button and the terminal's launcher address still provide access to approval management and room modes. - **Simpler connection settings:** Available NAT traversal enhancement now activates automatically. Advanced users can set `PIIK_STUN_URLS` to choose the STUN services used by App public invitations. - **Interface and icon polish:** Fixed narrow-screen room controls, nickname editing and overlays; simplified launcher guidance; aligned website language and theme controls with the App; and refreshed App icons and website favicons. In-page mascots and illustrations retain their existing appearance. - **Clearer connection troubleshooting:** Updated guidance distinguishes public-invitation service failures, Site access and media connectivity. This update preserves the 2.x communication protocols and database format. Browser capture can still recover slowly after some network disturbances; these fixes do not resolve every quality issue on every network or device.
147 lines
10 KiB
TypeScript
147 lines
10 KiB
TypeScript
import { spawn, type ChildProcessWithoutNullStreams } from "node:child_process";
|
|
import { once } from "node:events";
|
|
import { readFile, writeFile } from "node:fs/promises";
|
|
import { join, resolve } from "node:path";
|
|
import { createInterface } from "node:readline";
|
|
import { CdpConnection, cleanupRun, createPage, evaluate, fetchJsonBefore, launchChrome, reservePort, waitForSample,
|
|
waitForVersion, type PageHandle } from "../browser-gate-harness";
|
|
import { readAppEndpoint } from "../app-gate-endpoint";
|
|
import { pageProbe, type MediaSample } from "./page";
|
|
import { filteringProbe, preparePeerProbe, udpProbe } from "./udp";
|
|
|
|
export async function endpointWorker(): Promise<void> {
|
|
let chrome: ChildProcessWithoutNullStreams | null = null, app: ChildProcessWithoutNullStreams | null = null;
|
|
let cdp: CdpConnection | null = null, page: PageHandle | null = null;
|
|
const profile = process.env.PIIK_NETWORK_LAB_PROFILE;
|
|
if (!profile) throw new Error("Parent-owned browser profile is required");
|
|
const ports: number[] = [];
|
|
let rendezvous: Awaited<ReturnType<typeof preparePeerProbe>> | null = null;
|
|
const logs: Record<string, string> = {};
|
|
const log = (name: string, data: Buffer) => { logs[name] = ((logs[name] ?? "") + data).slice(-64_000); };
|
|
let closed = false;
|
|
const cleanup = async () => {
|
|
if (closed) return;
|
|
closed = true;
|
|
rendezvous?.close();
|
|
return cleanupRun({ chrome, native: app, cdp, server: null, profile, ports });
|
|
};
|
|
const sample = () => evaluate<MediaSample>(cdp!, page!, "networkLab.sample()", Date.now() + 5000);
|
|
const click = async (selector: string) => {
|
|
await waitForSample(deadline => evaluate<boolean>(cdp!, page!,
|
|
`Boolean(document.querySelector(${JSON.stringify(selector)}))`, deadline), Boolean, 10_000);
|
|
await evaluate(cdp!, page!, `document.querySelector(${JSON.stringify(selector)}).click()`, Date.now() + 5000);
|
|
};
|
|
try {
|
|
for await (const line of createInterface({ input: process.stdin })) {
|
|
const request = JSON.parse(line) as { id: number; action: string; origin?: string; app?: boolean;
|
|
url?: string; output?: string; delayMs?: number; load?: boolean; ipv6?: boolean; prediction?: boolean; sfuOnly?: boolean; peer?: { address: string; port: number } };
|
|
try {
|
|
let result: unknown;
|
|
if (request.action === "probe") {
|
|
result = await udpProbe(request.load === true, request.ipv6 === true);
|
|
} else if (request.action === "filter-probe") {
|
|
result = await filteringProbe();
|
|
} else if (request.action === "peer-prepare") {
|
|
rendezvous?.close(); rendezvous = await preparePeerProbe(); result = rendezvous.mapping;
|
|
} else if (request.action === "peer-probe") {
|
|
if (!rendezvous) throw new Error("Survey must precede peer probing");
|
|
result = await rendezvous.run(request.peer!);
|
|
} else if (request.action === "start") {
|
|
const origin = new URL(request.origin!).origin;
|
|
await waitForSample(deadline => fetchJsonBefore<{ status: string }>(`${origin}/healthz`, deadline),
|
|
value => value.status === "ok", 10_000);
|
|
if (request.app) {
|
|
app = spawn(resolve(`build/network-lab/bin/piik-app${process.platform === "win32" ? ".exe" : ""}`), ["--site", origin, "--debug", "--config", join(profile, "app.json")],
|
|
{ stdio: "pipe", windowsHide: true, env: { ...process.env, PIIK_CLIENT_GATE_NO_BROWSER: "true", PIIK_LOG_DIR: join(profile, "logs") } });
|
|
app.stderr.on("data", data => log("app", data));
|
|
await once(app, "spawn");
|
|
ports.push((await readAppEndpoint(app)).port); app.stdout.resume();
|
|
}
|
|
const debugPort = await reservePort(); ports.push(debugPort);
|
|
chrome = await launchChrome(process.env.CHROME_PATH!, debugPort, profile, [
|
|
"--headless=new", "--no-sandbox", "--disable-dev-shm-usage", "--no-first-run", "--no-default-browser-check",
|
|
"--no-proxy-server", "--autoplay-policy=no-user-gesture-required", "--disable-background-timer-throttling",
|
|
"--disable-renderer-backgrounding", "--disable-backgrounding-occluded-windows",
|
|
`--unsafely-treat-insecure-origin-as-secure=${origin}`,
|
|
]);
|
|
chrome.stdout.resume(); chrome.stderr.on("data", data => log("browser", data));
|
|
const version = await waitForVersion(debugPort, chrome);
|
|
cdp = await CdpConnection.connect(version.webSocketDebuggerUrl, Date.now() + 10_000);
|
|
await cdp.call("Browser.setPermission", { origin, permission: { name: "loopback-network" }, setting: "granted" }, undefined, Date.now() + 5000);
|
|
result = { browser: version.Browser, app: request.app === true, appPort: request.app ? ports[0] : null };
|
|
} else if (request.action === "navigate") {
|
|
if (page) {
|
|
const oldTimeOrigin = await evaluate<number>(cdp!, page!, "performance.timeOrigin", Date.now() + 5000);
|
|
const navigation = await cdp!.call<{ loaderId?: string; errorText?: string }>("Page.navigate", { url: request.url! }, page.sessionId, Date.now() + 5000);
|
|
if (navigation.errorText) throw new Error(navigation.errorText);
|
|
await waitForSample(deadline => evaluate<boolean>(cdp!, page!,
|
|
`${navigation.loaderId ? `performance.timeOrigin !== ${oldTimeOrigin} && ` : ""}document.readyState === 'complete' && Boolean(window.networkLab)`, deadline), Boolean, 10_000);
|
|
} else page = await createPage(cdp!, request.url!, pageProbe);
|
|
result = true;
|
|
} else if (request.action === "reload") {
|
|
const oldTimeOrigin = await evaluate<number>(cdp!, page!, "performance.timeOrigin", Date.now() + 5000);
|
|
await cdp!.call("Page.reload", {}, page!.sessionId, Date.now() + 5000);
|
|
await waitForSample(deadline => evaluate<boolean>(cdp!, page!,
|
|
`performance.timeOrigin !== ${oldTimeOrigin} && document.readyState === 'complete' && Boolean(window.networkLab)`, deadline), Boolean, 10_000);
|
|
result = true;
|
|
} else if (request.action === "share") {
|
|
const advanced = 'button[aria-controls="host-advanced-door"]';
|
|
await waitForSample(deadline => evaluate<boolean>(cdp!, page!,
|
|
`Boolean(document.querySelector(${JSON.stringify(advanced)}))`, deadline), Boolean, 10_000);
|
|
if (await evaluate<boolean>(cdp!, page!, `document.querySelector(${JSON.stringify(advanced)}).getAttribute('aria-expanded') !== 'true'`, Date.now() + 5000)) await click(advanced);
|
|
if (request.sfuOnly) {
|
|
if (request.prediction) throw new Error("SFU-only cannot request NAT enhancement");
|
|
await waitForSample(deadline => evaluate<boolean>(cdp!, page!,
|
|
`Boolean(document.querySelector('button[role="switch"][aria-label^="Server media"][aria-disabled="true"][aria-checked="true"]'))`, deadline), Boolean, 10_000);
|
|
}
|
|
// Browser-to-App encoded fanout is the production H264 path. VP8
|
|
// deliberately stays in the Browser and must not masquerade as App WAN.
|
|
await click(app ? 'button[aria-label^="H264"]' : 'button[aria-label^="VP8"]');
|
|
await click('button[aria-label="720p"]');
|
|
await click("button.lr-tv-big.is-action");
|
|
// Selecting Browser before App discovery completes intentionally uses
|
|
// Browser fanout. An App scenario waits for the real control session.
|
|
if (app) await waitForSample(deadline => evaluate<boolean>(cdp!, page!,
|
|
`Boolean(document.querySelector('.lr-source-picker-refresh:not(:disabled)')) && networkLab.sample().then(value => value.controlOpen)`,
|
|
deadline), Boolean, 10_000);
|
|
await click('button[data-source-tab="browser"]');
|
|
await click(".lr-source-option.is-browser");
|
|
await waitForSample(sample, value => value.sharing && value.width > 0 &&
|
|
(request.prediction === undefined || value.natPrediction === request.prediction), 30_000);
|
|
result = await evaluate<string>(cdp!, page!, "document.querySelector('.lr-invite-url').value", Date.now() + 5000);
|
|
} else if (request.action === "sample") {
|
|
result = await sample();
|
|
} else if (request.action === "delay-peer-signals") {
|
|
if (!Number.isInteger(request.delayMs) || request.delayMs! < 0 || request.delayMs! > 30_000) throw new Error("Invalid signal delay");
|
|
await evaluate(cdp!, page!, `networkLab.delayPeerSignals(${request.delayMs})`, Date.now() + 5000);
|
|
result = true;
|
|
} else if (request.action === "reset-playback-progress") {
|
|
await evaluate(cdp!, page!, "networkLab.resetPlaybackProgress()", Date.now() + 5000);
|
|
result = true;
|
|
} else if (request.action === "freeze-picture") {
|
|
result = await evaluate(cdp!, page!, "networkLab.freezeCapture()", Date.now() + 5000);
|
|
} else if (request.action === "resume-picture") {
|
|
result = await evaluate(cdp!, page!, "networkLab.resumeCapture()", Date.now() + 5000);
|
|
} else if (request.action === "signal-probe") {
|
|
result = await evaluate(cdp!, page!, "networkLab.signalProbe()", Date.now() + 5000);
|
|
} else if (request.action === "logs") {
|
|
if (app) logs.app = await readFile(join(profile, "logs", "client.log"), "utf8")
|
|
.then(text => text.slice(-64_000), error => String(error));
|
|
result = logs;
|
|
} else if (request.action === "stop") {
|
|
await click('button[aria-label="Stop sharing"]'); result = true;
|
|
} else if (request.action === "screenshot") {
|
|
const shot = await cdp!.call<{ data: string }>("Page.captureScreenshot", { format: "png" }, page!.sessionId, Date.now() + 5000);
|
|
await writeFile(request.output!, Buffer.from(shot.data, "base64")); result = true;
|
|
} else if (request.action === "close") {
|
|
result = await cleanup();
|
|
} else throw new Error("Unknown endpoint action");
|
|
process.stdout.write(JSON.stringify({ id: request.id, result }) + "\n");
|
|
if (closed) break;
|
|
} catch (error) {
|
|
process.stdout.write(JSON.stringify({ id: request.id, error: error instanceof Error ? error.message : String(error) }) + "\n");
|
|
}
|
|
}
|
|
} finally { await cleanup(); }
|
|
}
|