fix(app): improve capture selection and media recovery (#433)
## Problem and outcome / 问题与结果 This maintenance phase fixes failures around native capture startup, room reconnection and media handoffs. Capture mutations stay cancellable, relayed-content failures remain request-scoped, and failed media connections return to the existing route controller. Windows Auto codec selection measures delivered cadence instead of timer-sensitive per-frame work estimates. The phase preserves P2P-first routing, one committed graph and one route operation. It adds no signaling replay mechanism, changes no wire/schema version, and includes no interaction prototype or 4K feature work. ## Release notes ### 中文 Piik v1.6.8 是一次稳定性修复,重点改善 Windows 原生采集、断线恢复和分享过程中的控制响应。 #### 修复与改善 - **更准确地选择编码器。** Windows 的自动模式按实际出帧表现评估 H.264,并正确区分启动预热和持续性能不足,减少计时误差导致的不必要 VP8 回退。硬件编码事件改为异步等待。 - **改善断线与线路切换。** 房间信令短暂断开后保留观众成员身份 20 秒;修复线路切换、SFU 订阅恢复及声音重协商卡住的问题。失效连接及时交回现有路由控制器处理,原生 SFU 发送端不再把短暂断连直接判为终止。 - **保持 App 控制响应。** 开始分享和更换来源时仍可取消操作;合法消息突发不再直接关闭控制连接。中继信令的单条内容错误不会连带结束整场原生分享。 - **修正设备列表与配置保存。** 来源或麦克风数量达到上限时保留可用列表;配置替换失败时保留原有设置。 - **改善紧凑布局和辅助功能。** 调整手机横屏下的画面与播控布局、画质预设标签和长邀请链接显示,修正部分提示与辅助功能语义。 - **加强站点访问保护。** 站点登录 Cookie 使用独立随机签名密钥,应用自身阻止被其他页面嵌套。发布说明也会在合并前检查。 #### 升级说明 通信协议和持久化格式保持不变。设置了站点密码时,App 或 Server 重启后需要重新输入站点密码;持久化房间和邀请授权不受这项 Cookie 调整影响。Piik 操作页面不再支持嵌入 iframe。 ### English Piik v1.6.8 is a stability update focused on Windows native capture, connection recovery and responsive sharing controls. #### Fixes and improvements - **More accurate codec selection.** Windows Auto mode evaluates H.264 using delivered frames and distinguishes startup warmup from sustained performance limits, reducing unnecessary VP8 fallback caused by timing noise. Hardware encoder events now use asynchronous waiting. - **Improved reconnection and route handoffs.** Viewer membership survives brief signaling outages for 20 seconds. Fixes cover route activation, SFU subscription recovery and stalled audio renegotiation. Failed connections return to the existing route controller, and the native SFU publisher no longer treats a transient disconnect as immediate termination. - **Responsive App controls.** Starting a share and replacing its source remain cancellable. Valid message bursts no longer close the control connection, and an invalid relayed payload cannot terminate the entire native sharing session. - **Device lists and saved settings.** Source and microphone enumeration retain a usable list at their limits. Failed configuration replacement preserves the previous settings. - **Compact layouts and accessibility.** Improved picture and playback-control layout on landscape phones, quality preset labels and long invitation links, with corrected tooltip and accessibility semantics. - **Stronger site-access protection.** Login cookies use an independent random signing key, and the application prevents embedding by other pages. Release notes are also checked before merge. #### Upgrade notes Wire protocols and persistent formats are unchanged. If a site password is configured, restarting the App or Server requires entering it again; this cookie change does not revoke persisted rooms or invitation grants. Piik operation pages can no longer be embedded in an iframe. ## Verification / 验证 - `npm run check`: passed, 76 test files / 1,171 tests, TypeScript and production Web build. - `npm run check:go-core`: passed; full Go/native checks also passed during integration of the capture changes. macOS cgo builds remain native-runner checks. - Windows native Host gates: Auto, H.264 and VP8 passed during the phase; final control changes rechecked with Auto, including live/paused quality, source replacement, failure retirement and subsequent sharing. - Embedded SFU browser VP8 recovery: passed with production Host/Viewer route owners. - Embedded SFU native H.264, two rooms: passed, including recovered decoded video/audio, independent room retirement and resource cleanup. - Documentation, repository hygiene and diff checks: passed. Final follow-up changes only align operations documentation with the PR note check. - Go race checks could not run locally because no cgo/GCC toolchain is available; the existing Linux CI race job remains required. AMD/Intel hardware, broader device combinations, public-NAT field reports and long endurance are not established by these local checks. ## Impact / 影响 Compatible patch release after v1.6.7. The cookie and frame-protection effects are disclosed in the public upgrade notes. No automatic retry budget, room-code admission policy, room lifetime or media topology is replaced. Reports without matched diagnostics and unmeasured native performance costs remain in the TODO ledger.
This commit is contained in:
73 files changed
+2001
-676
No files matched your search
@@ -89,11 +89,11 @@ async function main(): Promise<void> {
|
||||
startedAt: new Date().toISOString(), finishedAt: "", processes: [] as Array<{ role: string; pid: number | null }>,
|
||||
high: null as { frames: number; width: number; height: number } | null,
|
||||
low: null as { frames: number; width: number; height: number } | null,
|
||||
audioEnergy: { high: 0, low: 0 },
|
||||
audioEnergy: { high: 0, low: 0, recovered: 0 },
|
||||
audioDiagnostics: null as unknown,
|
||||
secondRoom: twoRooms ? { connected: false, framesAfterFirstStopped: 0, audioBefore: 0, audioAfter: 0, stopped: false } : null,
|
||||
host: null as Snapshot | null, viewer: null as Snapshot | null,
|
||||
publicationRetired: false, nativeShareStopped: !nativeArm, udpReleased: false, cleanup: false, error: null as string | null };
|
||||
publicationRetired: false, subscriptionRecovered: false, nativeShareStopped: !nativeArm, udpReleased: false, cleanup: false, error: null as string | null };
|
||||
let server: ChildProcessWithoutNullStreams | null = null;
|
||||
let chrome: ChildProcessWithoutNullStreams | null = null;
|
||||
let vite: ViteDevServer | null = null;
|
||||
@@ -132,13 +132,14 @@ async function main(): Promise<void> {
|
||||
try {
|
||||
server = spawn(binary, [], { cwd: ROOT, stdio: "pipe", windowsHide: true,
|
||||
env: { PATH: process.env.PATH, SystemRoot: process.env.SystemRoot,
|
||||
PIIK_ENV: "development", LISTEN_HOST: "127.0.0.1", PORT: String(serverPort),
|
||||
PIIK_ENV: "development", PIIK_DEBUG: "route", LISTEN_HOST: "127.0.0.1", PORT: String(serverPort),
|
||||
PIIK_LOG_DIR: join(BUILD_ROOT, "logs"),
|
||||
PUBLIC_BASE_URL: origin, ALLOWED_ORIGINS: origin,
|
||||
SFU_LISTEN_HOST: "127.0.0.1", SFU_UDP_PORT: String(mediaPort), SFU_PUBLIC_IP: "127.0.0.1" },
|
||||
});
|
||||
processStarted("server", server);
|
||||
server.stdout.resume();
|
||||
server.stderr.on("data", (data: Buffer) => { serverError = (serverError + data.toString()).slice(-2000); });
|
||||
server.stderr.on("data", (data: Buffer) => { serverError = (serverError + data.toString()).slice(-16000); });
|
||||
await waitForSample((deadline) => fetchJsonBefore<{ status: string }>(`${backend}/healthz`, deadline),
|
||||
() => true, 15_000);
|
||||
vite = await createViteServer({ root: ROOT, configFile: false, appType: "custom", logLevel: "silent",
|
||||
@@ -241,6 +242,18 @@ async function main(): Promise<void> {
|
||||
result.low = await call(viewer, "gate.waitForFrames(854, 480)");
|
||||
await waitForSample(() => call<number>(viewer!, "gate.audioEnergy()", 3_000),
|
||||
(energy) => { result.audioEnergy.low = energy; return energy > result.audioEnergy.high; }, 5_000);
|
||||
result.stage = "committed-subscription-recovery";
|
||||
const previousSubscription = await call<string>(viewer, "gate.failSubscription()");
|
||||
// Terminal failure consumes this exact opportunity. A new authenticated
|
||||
// session reopens acquisition; configuration refresh alone cannot do so.
|
||||
await until(viewer, value => value.routeStatus === "failed");
|
||||
await call(viewer, `gate.reconnectViewer(${JSON.stringify(room)})`);
|
||||
await until(viewer, value => value.committed && value.connectionId !== previousSubscription && value.audioKbps > 0);
|
||||
await call(viewer, "gate.waitForFrames(854, 480)");
|
||||
await waitForSample(() => call<number>(viewer!, "gate.audioEnergy()", 3_000),
|
||||
energy => { result.audioEnergy.recovered = energy; return energy > 0; }, 5_000);
|
||||
result.viewer = await call(viewer, "gate.snapshot()");
|
||||
result.subscriptionRecovered = true;
|
||||
result.stage = "publication-retirement";
|
||||
await call(host, "gate.stopSharing()");
|
||||
await until(host, (value) => value.publicationRetired);
|
||||
@@ -265,9 +278,10 @@ async function main(): Promise<void> {
|
||||
}
|
||||
} catch (error) {
|
||||
result.error = error instanceof Error ? error.message : String(error);
|
||||
if (viewer && cdp) result.viewer = await call<Snapshot>(viewer, "gate.snapshot()", 3_000).catch(() => null);
|
||||
if (viewer && cdp && result.stage === "decoded-audio-energy") result.audioDiagnostics = await evaluate(
|
||||
cdp, viewer, "window.__piikGateAudioStats ?? null", Date.now() + 3_000).catch(() => null);
|
||||
if (server?.exitCode !== null && serverError) result.error += `; server: ${serverError}`;
|
||||
if (serverError) result.error += `; server: ${serverError}`;
|
||||
} finally {
|
||||
const pagesStopped = await Promise.all([host, viewer, secondHost, secondViewer].map((page) =>
|
||||
page && cdp ? call<boolean>(page, "gate.stop()", 5_000).catch(() => false) : true));
|
||||
@@ -291,8 +305,8 @@ async function main(): Promise<void> {
|
||||
result.passed = !result.error && result.host?.published === true && result.host.simulcast &&
|
||||
result.viewer?.decoded === true && result.viewer.committed && result.viewer.peerFailures > 0 &&
|
||||
result.viewer.audioKbps > 0 && result.audioEnergy.high > 0 && result.audioEnergy.low > result.audioEnergy.high &&
|
||||
result.high !== null && result.low !== null &&
|
||||
result.publicationRetired && result.cleanup && result.nativeShareStopped &&
|
||||
result.high !== null && result.low !== null && result.audioEnergy.recovered > 0 &&
|
||||
result.publicationRetired && result.subscriptionRecovered && result.cleanup && result.nativeShareStopped &&
|
||||
(!result.secondRoom || result.secondRoom.connected && result.secondRoom.framesAfterFirstStopped >= 30 &&
|
||||
result.secondRoom.audioBefore > 0 && result.secondRoom.audioAfter > result.secondRoom.audioBefore && result.secondRoom.stopped) &&
|
||||
(!nativeArm || result.host.nativeShareStarted && result.host.nativeFramesPerSecond > 0 && result.host.nativeBitrateKbps > 0 && result.host.nativeEncodingCount === 2);
|
||||
|
||||
+111
-77
@@ -14,7 +14,8 @@ import type { SfuConnectionConfig } from "../src/client/sfu/peer";
|
||||
import { NativeClient } from "../src/client/native/client";
|
||||
import { NativeSfuPublisher } from "../src/client/native/native-sfu-publisher";
|
||||
import { defaultNativeCapturePath } from "../src/client/native/capture-selection";
|
||||
import type { HostPublisherTransport } from "../src/client/media/host-sfu-route";
|
||||
import { HostSfuRoute, type HostPublisherTransport } from "../src/client/media/host-sfu-route";
|
||||
import { ViewerSfuRoute } from "../src/client/media/viewer-sfu-route";
|
||||
|
||||
const high: QualitySettings = {
|
||||
resolution: "720p", maxFramerate: 15, maxBitrate: 2_000_000,
|
||||
@@ -22,6 +23,7 @@ const high: QualitySettings = {
|
||||
};
|
||||
const low: QualitySettings = { ...high, resolution: "480p" };
|
||||
const shareGeneration = crypto.randomUUID();
|
||||
const clientId = crypto.randomUUID();
|
||||
let socket: WebSocket | null = null;
|
||||
let publisher: HostPublisherTransport | null = null;
|
||||
let native: NativeClient | null = null;
|
||||
@@ -30,14 +32,16 @@ let nativeShareStopped = false;
|
||||
let nativeFramesPerSecond = 0;
|
||||
let nativeBitrateKbps = 0;
|
||||
let nativeEncodingCount = 0;
|
||||
let subscriber: SfuSubscriber | null = null;
|
||||
let viewerRoute: ViewerSfuRoute | null = null;
|
||||
let hostRoute: HostSfuRoute | null = null;
|
||||
let profile = high;
|
||||
let failSubscriber: (() => void) | null = null;
|
||||
let configuration: SfuConnectionConfig | null = null;
|
||||
let source: MediaStream | null = null;
|
||||
let audio: AudioContext | null = null;
|
||||
let canvas: HTMLCanvasElement | null = null;
|
||||
let video: HTMLVideoElement | null = null;
|
||||
let drawTimer: number | null = null;
|
||||
let preparedRevision = 0;
|
||||
let decoded = false;
|
||||
let authenticated = false;
|
||||
let committed = false;
|
||||
@@ -52,10 +56,19 @@ let audioKbps = 0;
|
||||
let audioCodec: string | null = null;
|
||||
let error: string | null = null;
|
||||
let messageTail = Promise.resolve();
|
||||
let routeStatus: string | null = null;
|
||||
const routeEvents: Array<{ type: string; revision?: number; phase?: string; connectionId?: string | null }> = [];
|
||||
|
||||
function traceRoute(message: { type: string; revision?: number; phase?: string; connectionId?: string | null }): void {
|
||||
routeEvents.push({ type: message.type, revision: message.revision, phase: message.phase, connectionId: message.connectionId });
|
||||
if (routeEvents.length > 20) routeEvents.shift();
|
||||
}
|
||||
|
||||
function send(message: ClientMessage): boolean {
|
||||
clientMessageSchema.parse(message);
|
||||
if (socket?.readyState !== WebSocket.OPEN) return false;
|
||||
if (message.type === "route-failed" || message.type === "route-ready") traceRoute(message);
|
||||
if (message.type === "sfu-signal" && message.kind !== "candidate") traceRoute({ ...message, type: `send-${message.kind}` });
|
||||
if (message.type === "sfu-signal" && message.description?.type === "offer") {
|
||||
simulcast = message.description.sdp.includes("a=simulcast:send q;h");
|
||||
}
|
||||
@@ -68,106 +81,105 @@ function failed(reason: unknown): void {
|
||||
}
|
||||
|
||||
async function accept(message: ServerMessage, host: boolean): Promise<void> {
|
||||
if (message.type === "route-update" || message.type === "sfu-config" || message.type === "route-status") traceRoute(message);
|
||||
if (message.type === "route-status") routeStatus = message.state;
|
||||
if (message.type === "sfu-signal" && message.kind !== "candidate") traceRoute({ ...message, type: `receive-${message.kind}` });
|
||||
if (message.type === "error") throw new Error(`${message.code}: ${message.message}`);
|
||||
if (message.type === "authenticated") authenticated = true;
|
||||
if (message.type === "authenticated") {
|
||||
authenticated = true;
|
||||
if (host && !hostRoute) hostRoute = new HostSfuRoute({
|
||||
send, getStream: () => source, getProfile: () => profile,
|
||||
getVideoCodec: () => codec, reconcileChildren: () => undefined,
|
||||
createPublisher: (onDisconnected, onStats) => {
|
||||
publisher = native
|
||||
? new NativeSfuPublisher(native, shareGeneration, { iceServers: [] }, {
|
||||
send, onDisconnected, onStats: metrics => {
|
||||
onStats(metrics);
|
||||
nativeFramesPerSecond = metrics?.framesPerSecond ?? 0;
|
||||
nativeBitrateKbps = metrics?.bitrateKbps ?? 0;
|
||||
nativeEncodingCount = metrics?.videoEncodingCount ?? 0;
|
||||
},
|
||||
})
|
||||
: new SfuPublisher({ send, onDisconnected, onStats });
|
||||
return publisher;
|
||||
},
|
||||
});
|
||||
await hostRoute?.resyncAuthoritative({ revision: message.routeRevision,
|
||||
phase: "active", assignment: message.routeAssignment });
|
||||
if (!host && !viewerRoute) {
|
||||
video = document.createElement("video");
|
||||
video.volume = 0.1;
|
||||
video.autoplay = true;
|
||||
video.playsInline = true;
|
||||
video.style.cssText = "max-width:100%;width:640px";
|
||||
document.body.append(video);
|
||||
viewerRoute = new ViewerSfuRoute(message.peerId, {
|
||||
send, activatePeer: () => true,
|
||||
onSfuStream: stream => {
|
||||
decoded = committed = true;
|
||||
if (video && video.srcObject !== stream) {
|
||||
video.srcObject = stream;
|
||||
void video.play().catch(failed);
|
||||
}
|
||||
},
|
||||
onSfuUpdate: metrics => {
|
||||
audioKbps = metrics?.audioBitrateKbps ?? 0;
|
||||
audioCodec = metrics?.audioCodec ?? null;
|
||||
},
|
||||
createSubscriber: events => {
|
||||
const transport = new SfuSubscriber({ ...events, send,
|
||||
onState: state => { traceRoute({ type: `media-${state}` }); events.onState(state); },
|
||||
onFirstDecodedFrame: () => { traceRoute({ type: "decoded-frame" }); return events.onFirstDecodedFrame(); },
|
||||
});
|
||||
failSubscriber = () => { void transport.disconnect(); events.onDisconnected(); };
|
||||
return transport;
|
||||
},
|
||||
});
|
||||
}
|
||||
await viewerRoute?.resyncAuthoritative({ revision: message.routeRevision,
|
||||
phase: "active", assignment: message.routeAssignment }, message.peerId);
|
||||
}
|
||||
if (message.type === "sharing-stopped") {
|
||||
sharingStopped = true;
|
||||
await subscriber?.disconnect();
|
||||
await viewerRoute?.disconnect();
|
||||
}
|
||||
if (message.type === "route-update") {
|
||||
if (message.phase === "prepare") routeStatus = null;
|
||||
viewerRoute?.accept(message);
|
||||
await hostRoute?.acceptAndWait(message);
|
||||
if (message.phase === "prepare" && !host) {
|
||||
if (message.candidate.transport === "direct") {
|
||||
// Exercise the ordinary fallback operation without changing room policy.
|
||||
peerFailures += 1;
|
||||
send({ type: "route-failed", revision: message.revision,
|
||||
phase: "prepare", connectionId: message.candidate.connectionId });
|
||||
} else preparedRevision = message.revision;
|
||||
}
|
||||
if (message.phase === "active") {
|
||||
if (!host && message.assignment.upstream.kind === "sfu") {
|
||||
if (!decoded) throw new Error("SFU committed before decoded-frame proof");
|
||||
committed = true;
|
||||
}
|
||||
if (configuration && message.assignment.sfuPublicationGeneration === configuration.publicationGeneration) {
|
||||
configuration = { ...configuration, revision: message.revision };
|
||||
publisher?.updateConfig(configuration);
|
||||
subscriber?.updateConfig(configuration);
|
||||
}
|
||||
}
|
||||
}
|
||||
if (message.type === "sfu-config") {
|
||||
if (configuration) {
|
||||
if (configuration.connectionId !== message.connectionId ||
|
||||
configuration.publicationGeneration !== message.publicationGeneration) {
|
||||
throw new Error("Unexpected SFU replacement during bounded acceptance");
|
||||
}
|
||||
configuration = message;
|
||||
publisher?.updateConfig(message);
|
||||
subscriber?.updateConfig(message);
|
||||
return;
|
||||
}
|
||||
configuration = message;
|
||||
if (host) {
|
||||
const events = { send, onDisconnected: () => {
|
||||
if (!stopping) failed("Publisher disconnected");
|
||||
} };
|
||||
publisher = native
|
||||
? new NativeSfuPublisher(native, shareGeneration, { iceServers: [] }, { ...events,
|
||||
onStats: (metrics) => {
|
||||
nativeFramesPerSecond = metrics?.framesPerSecond ?? 0;
|
||||
nativeBitrateKbps = metrics?.bitrateKbps ?? 0;
|
||||
nativeEncodingCount = metrics?.videoEncodingCount ?? 0;
|
||||
},
|
||||
})
|
||||
: new SfuPublisher(events);
|
||||
await publisher.connect(message);
|
||||
published = await publisher.activate(source!, high, codec);
|
||||
if (!published) throw new Error("Publisher did not activate");
|
||||
} else {
|
||||
video = document.createElement("video");
|
||||
video.muted = false;
|
||||
video.volume = 0.1;
|
||||
video.autoplay = true;
|
||||
video.playsInline = true;
|
||||
video.style.cssText = "max-width:100%;width:640px";
|
||||
document.body.append(video);
|
||||
subscriber = new SfuSubscriber({
|
||||
send,
|
||||
onStream: (stream) => {
|
||||
if (!video || video.srcObject === stream) return;
|
||||
video.srcObject = stream;
|
||||
if (stream) void video.play().catch(failed);
|
||||
},
|
||||
onStats: (metrics) => {
|
||||
audioKbps = metrics.audioBitrateKbps ?? 0;
|
||||
audioCodec = metrics.audioCodec;
|
||||
},
|
||||
onFirstDecodedFrame: () => {
|
||||
decoded = true;
|
||||
return send({ type: "route-ready", revision: preparedRevision, phase: "prepare" });
|
||||
},
|
||||
onDisconnected: () => { if (!sharingStopped) failed("Subscriber disconnected"); },
|
||||
});
|
||||
await subscriber.connect(message);
|
||||
subscriber.armDecodedFrameProof();
|
||||
subscriber.activate();
|
||||
}
|
||||
await hostRoute?.acceptConfig(message);
|
||||
published = publisher !== null;
|
||||
} else await viewerRoute?.acceptConfig(message);
|
||||
}
|
||||
if (message.type === "sfu-signal") {
|
||||
await publisher?.acceptSignal(message);
|
||||
await subscriber?.acceptSignal(message);
|
||||
await hostRoute?.acceptSignal(message);
|
||||
await viewerRoute?.acceptSignal(message);
|
||||
}
|
||||
}
|
||||
|
||||
async function connect(room: CreateRoomResponse, host: boolean): Promise<void> {
|
||||
socket = new WebSocket(new URL("/signal", location.href).href.replace(/^http/, "ws"));
|
||||
const connection = socket;
|
||||
socket.addEventListener("message", ({ data }) => {
|
||||
messageTail = messageTail.then(() => accept(decodeServerMessage(String(data)), host)).catch(failed);
|
||||
});
|
||||
socket.addEventListener("error", () => failed("Room WebSocket failed"));
|
||||
socket.addEventListener("close", (event) => {
|
||||
if (socket !== connection) return;
|
||||
if (host && stopping && event.code === 1000 && event.reason === "Sharing stopped") {
|
||||
void publisher?.disconnect().then(() => { publicationRetired = true; });
|
||||
void hostRoute?.disconnect().then(() => { publicationRetired = true; });
|
||||
} else if (!stopping && !sharingStopped) failed(`Unexpected room socket close: ${event.code}`);
|
||||
});
|
||||
await new Promise<void>((resolve, reject) => {
|
||||
@@ -175,7 +187,7 @@ async function connect(room: CreateRoomResponse, host: boolean): Promise<void> {
|
||||
socket!.addEventListener("open", () => { clearTimeout(timer); resolve(); }, { once: true });
|
||||
});
|
||||
const common = { type: "authenticate", protocol: SIGNALING_PROTOCOL,
|
||||
roomId: room.roomId, clientId: crypto.randomUUID() } as const;
|
||||
roomId: room.roomId, clientId } as const;
|
||||
send(host
|
||||
? { ...common, role: "host", token: room.hostToken, shareGeneration,
|
||||
qualitySettings: high, routePolicy: { peerOnly: false, topologyOptimization: false, natPrediction: false } }
|
||||
@@ -202,6 +214,7 @@ export async function startHost(nativeSource?: { title: string; port: number },
|
||||
const started = await native.startShare({ shareId: shareGeneration, source: target,
|
||||
codec, audio: true, profile: high, edgeCapacity: 2, ...path });
|
||||
nativeShareStarted = true;
|
||||
source = new MediaStream();
|
||||
if (started.codec !== codec || !started.audio) throw new Error("Requested Native codec and Opus capture did not start");
|
||||
await connect(room, true);
|
||||
return room;
|
||||
@@ -240,14 +253,34 @@ export async function startViewer(room: CreateRoomResponse): Promise<void> {
|
||||
await connect(room, false);
|
||||
}
|
||||
|
||||
export async function reconnectViewer(room: CreateRoomResponse): Promise<void> {
|
||||
const previous = socket;
|
||||
socket = null;
|
||||
previous?.close();
|
||||
authenticated = false;
|
||||
await connect(room, false);
|
||||
}
|
||||
|
||||
export function snapshot() {
|
||||
return { authenticated, published, simulcast, decoded, committed, peerFailures,
|
||||
routeEvents, routeStatus,
|
||||
connectionId: configuration?.connectionId,
|
||||
audioKbps, audioCodec, publicationRetired, sharingStopped, nativeShareStarted, nativeShareStopped,
|
||||
nativeFramesPerSecond, nativeBitrateKbps, nativeEncodingCount,
|
||||
warning: publisher?.getQualityWarning?.() ?? null,
|
||||
failureStage: publisher?.getFailureStage?.() ?? null, error };
|
||||
}
|
||||
|
||||
// Fault injection retires real media; the production route owner must negotiate
|
||||
// and decode on a new server-owned edge before the gate counts recovery.
|
||||
export function failSubscription(): string {
|
||||
if (!failSubscriber || !configuration || !committed) throw new Error("No active subscription");
|
||||
const previous = configuration.connectionId;
|
||||
decoded = committed = false;
|
||||
failSubscriber();
|
||||
return previous;
|
||||
}
|
||||
|
||||
export async function audioEnergy(): Promise<number> {
|
||||
const probe = (window as unknown as { __piikGateAudioEnergy: () => Promise<number> }).__piikGateAudioEnergy;
|
||||
return await probe();
|
||||
@@ -283,8 +316,9 @@ export async function lowerProfile(): Promise<boolean> {
|
||||
canvas.width = 854;
|
||||
canvas.height = 480;
|
||||
}
|
||||
profile = low;
|
||||
send({ type: "set-quality-settings", qualitySettings: low });
|
||||
return await publisher.updateProfile(low);
|
||||
return await hostRoute!.updateProfile(low);
|
||||
}
|
||||
|
||||
export function stopSharing(): void {
|
||||
@@ -294,8 +328,8 @@ export function stopSharing(): void {
|
||||
|
||||
export async function stop(): Promise<boolean> {
|
||||
stopping = true;
|
||||
await publisher?.disconnect();
|
||||
await subscriber?.disconnect();
|
||||
await hostRoute?.disconnect();
|
||||
await viewerRoute?.disconnect();
|
||||
if (native) {
|
||||
if (nativeShareStarted) {
|
||||
await native.stopShare(shareGeneration);
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
import { execFileSync } from "node:child_process";
|
||||
import { createHash } from "node:crypto";
|
||||
import { openAsBlob } from "node:fs";
|
||||
import { setTimeout as delay } from "node:timers/promises";
|
||||
import { readReleaseArtifacts } from "./release-artifacts.mjs";
|
||||
|
||||
const [directory, version, revision, option] = process.argv.slice(2);
|
||||
@@ -14,14 +15,30 @@ const api = `https://gitee.com/api/v5/repos/${repository}`;
|
||||
const marker = `<!-- piik-source: ${revision} -->`;
|
||||
const token = process.env.GITEE_TOKEN?.trim();
|
||||
|
||||
async function fetchResponse(url, options, timeout) {
|
||||
const attempts = (options.method ?? "GET") === "GET" ? 3 : 1;
|
||||
for (let attempt = 1; ; attempt++) {
|
||||
try {
|
||||
const response = await fetch(url, { ...options, signal: AbortSignal.timeout(timeout) });
|
||||
if (attempt === attempts || ![408, 429, 500, 502, 503, 504].includes(response.status)) return response;
|
||||
await response.body?.cancel();
|
||||
} catch (error) {
|
||||
if (attempt === attempts || !(error instanceof TypeError || error?.name === "TimeoutError")) throw error;
|
||||
}
|
||||
await delay(attempt * 1_000);
|
||||
}
|
||||
}
|
||||
|
||||
async function request(path, method = "GET", body) {
|
||||
const multipart = body instanceof FormData;
|
||||
const response = await fetch(api + path, {
|
||||
method, redirect: "error", signal: AbortSignal.timeout(multipart ? 180_000 : 20_000),
|
||||
// A timed-out upload may already exist. Retry only reads; a script rerun
|
||||
// reconciles attachment identities before any subsequent write.
|
||||
const response = await fetchResponse(api + path, {
|
||||
method, redirect: "error",
|
||||
headers: { Accept: "application/json", Authorization: `Bearer ${token}`,
|
||||
...(!body || multipart ? {} : { "Content-Type": "application/json" }) },
|
||||
body: body ? multipart ? body : JSON.stringify(body) : undefined,
|
||||
});
|
||||
}, multipart ? 180_000 : 20_000);
|
||||
if (response.status === 404 && method === "GET") return null;
|
||||
if (!response.ok) throw new Error(`Gitee ${method} ${path}: HTTP ${response.status}`);
|
||||
return response.json();
|
||||
@@ -33,7 +50,7 @@ async function verifyDownload(uploaded, file) {
|
||||
if (uploaded?.size !== file.size || uploaded.browser_download_url !== expectedURL) {
|
||||
throw new Error(`Mirror attachment metadata mismatch: ${file.name}`);
|
||||
}
|
||||
const response = await fetch(expectedURL, { signal: AbortSignal.timeout(180_000) });
|
||||
const response = await fetchResponse(expectedURL, {}, 180_000);
|
||||
if (!response.ok || !response.body) throw new Error(`Mirror attachment is not anonymously downloadable: ${file.name}`);
|
||||
const hash = createHash("sha256");
|
||||
let size = 0;
|
||||
|
||||
+41
-21
@@ -1,7 +1,29 @@
|
||||
import { appendFileSync } from "node:fs";
|
||||
import { appendFileSync, readFileSync } from "node:fs";
|
||||
import { pathToFileURL } from "node:url";
|
||||
import semver from "semver";
|
||||
import { isReleaseVersion, releaseCommits, stableTags } from "./release-version.mjs";
|
||||
import { hasProductChanges, isReleaseVersion, releaseCommits, stableTags } from "./release-version.mjs";
|
||||
|
||||
export function releaseNotesSection(message, source) {
|
||||
const sections = message.replace(/\r\n/g, "\n").split(/^## /m).slice(1)
|
||||
.filter((section) => section.split("\n", 1)[0].trim() === "Release notes");
|
||||
const body = sections.length === 1
|
||||
? sections[0].split("\n").slice(1).join("\n").replace(/<!--[\s\S]*?-->/g, "").trim()
|
||||
: "";
|
||||
if (!body || !body.split("\n").some((line) => line.trim() && !/^#{1,6}(\s|$)/.test(line))) {
|
||||
throw new Error(`${source} needs one nonempty ## Release notes section`);
|
||||
}
|
||||
if (/\uFFFD|\?{3,}/u.test(body)) {
|
||||
throw new Error(`${source} has damaged Release notes text; restore the UTF-8 source`);
|
||||
}
|
||||
return body;
|
||||
}
|
||||
|
||||
export function pullRequestNotes(root, event) {
|
||||
const pr = event.pull_request;
|
||||
if (!pr) throw new Error("A pull_request event is required");
|
||||
return hasProductChanges(root, pr.base.sha, pr.head.sha)
|
||||
? releaseNotesSection(pr.body ?? "", `PR #${pr.number}`) : "";
|
||||
}
|
||||
|
||||
// The reviewed PR body survives the squash commit. Only its public section is
|
||||
// release copy; implementation details and verification logs stay in the PR.
|
||||
@@ -14,15 +36,7 @@ export function releaseNotes(root, version, revision, repository, { allowEmpty =
|
||||
const previous = stableTags(root, "--merged", revision).find((tag) => semver.lt(tag, version));
|
||||
const bodies = [];
|
||||
for (const commit of releaseCommits(root, revision, previous)) {
|
||||
const sections = commit.message.replace(/\r\n/g, "\n").split(/^## /m).slice(1)
|
||||
.filter((section) => section.split("\n", 1)[0].trim() === "Release notes");
|
||||
const body = sections.length === 1
|
||||
? sections[0].split("\n").slice(1).join("\n").replace(/<!--[\s\S]*?-->/g, "").trim()
|
||||
: "";
|
||||
if (!body || !body.split("\n").some((line) => line.trim() && !/^#{1,6}(\s|$)/.test(line))) {
|
||||
throw new Error(`Commit ${commit.revision} needs one nonempty ## Release notes section`);
|
||||
}
|
||||
bodies.push(body);
|
||||
bodies.push(releaseNotesSection(commit.message, `Commit ${commit.revision}`));
|
||||
}
|
||||
if (!bodies.length) {
|
||||
if (allowEmpty) return "";
|
||||
@@ -37,15 +51,21 @@ export function releaseNotes(root, version, revision, repository, { allowEmpty =
|
||||
|
||||
if (process.argv[1] && import.meta.url === pathToFileURL(process.argv[1]).href) {
|
||||
const [version, revision, option] = process.argv.slice(2);
|
||||
if (option && option !== "--github-summary") {
|
||||
throw new Error("Use release-notes.mjs <version> <full-SHA> [--github-summary]");
|
||||
if (version === "--pull-request") {
|
||||
if (!process.env.GITHUB_EVENT_PATH) throw new Error("GITHUB_EVENT_PATH is missing");
|
||||
pullRequestNotes(process.cwd(), JSON.parse(readFileSync(process.env.GITHUB_EVENT_PATH, "utf8")));
|
||||
process.stdout.write("PR release notes validated.\n");
|
||||
} else {
|
||||
if (option && option !== "--github-summary") {
|
||||
throw new Error("Use release-notes.mjs <version> <full-SHA> [--github-summary]");
|
||||
}
|
||||
const body = releaseNotes(process.cwd(), version, revision,
|
||||
process.env.GITHUB_REPOSITORY || "TNTcraftHIM/Piik", { allowEmpty: Boolean(option) });
|
||||
if (option) {
|
||||
if (!process.env.GITHUB_STEP_SUMMARY) throw new Error("GITHUB_STEP_SUMMARY is missing");
|
||||
appendFileSync(process.env.GITHUB_STEP_SUMMARY,
|
||||
`## Release notes preview: Piik ${version}\n\n${body || "No product changes; this candidate does not publish a release.\n"}`);
|
||||
}
|
||||
process.stdout.write(body);
|
||||
}
|
||||
const body = releaseNotes(process.cwd(), version, revision,
|
||||
process.env.GITHUB_REPOSITORY || "TNTcraftHIM/Piik", { allowEmpty: Boolean(option) });
|
||||
if (option) {
|
||||
if (!process.env.GITHUB_STEP_SUMMARY) throw new Error("GITHUB_STEP_SUMMARY is missing");
|
||||
appendFileSync(process.env.GITHUB_STEP_SUMMARY,
|
||||
`## Release notes preview: Piik ${version}\n\n${body || "No product changes; this candidate does not publish a release.\n"}`);
|
||||
}
|
||||
process.stdout.write(body);
|
||||
}
|
||||
@@ -28,6 +28,13 @@ const nonProductPaths = [
|
||||
"cmd/piik-peer-gate/**",
|
||||
].map((path) => `:(top,glob,exclude)${path}`);
|
||||
|
||||
export function hasProductChanges(root, base, head) {
|
||||
if (![base, head].every(value => /^[a-f0-9]{40}$/.test(value))) {
|
||||
throw new Error("Product comparison requires full commit SHAs");
|
||||
}
|
||||
return git(root, "diff", "--name-only", "--no-renames", `${base}...${head}`, "--", ".", ...nonProductPaths) !== "";
|
||||
}
|
||||
|
||||
// Both version selection and public notes use this same set of product commits.
|
||||
// Git handles deletions and moves across the boundary; no workflow path filter
|
||||
// can hide an earlier product change whose publication needs to be retried.
|
||||
|
||||
Reference in new issue
Block a user