This maintenance phase corrects connection and media recovery after startup deadlines, congestion and packet loss. Route selection remains a bounded operation; Pion and LiveKit continue to own congestion control, adaptation and retransmission. Changes stay within existing owners: - Preserve an untried SFU fallback when a connected P2P candidate produces no first frame before its deadline. Retire expired native preparations using the current edge identity. - Correct paced output, probe accounting and partial-recovery demand. Negotiate RTX consistently for native forwarding and SFU publication, including repaired stream identifiers for simulcast. - Return working IPv4 mappings without waiting for optional IPv6 work, and separate NAT observations by the local socket/address that produced them. - Keep optional App availability separate from basic source selection; stabilize nickname/chat layouts and restore volume from zero correctly. - Retry complete Gitee reads, including response bodies and hash verification. Ambiguous uploads remain single attempts and are reconciled against the remote inventory before rerunning. Related: #468, #464, #471. The repairs affect paths discussed in these reports; incomplete field diagnostics do not establish that each report has the same cause, so this PR does not automatically close them. ## Validation - Web type checks, production build and 1,624 tests passed. Go core, formatting, vet and local target builds passed. - Delayed RTX recovery reproduced the defect before the fix; the repaired-SSRC mutation also fails the focused regression. Real Windows H.264 and VP8 capture passed the SFU gates, including settings, reload recovery and retirement. - The media lifecycle gate passed all 14 trials across Browser/App pairings and P2P/SFU handoffs. Native connectivity, paced forwarding and negative-control checks passed. - Responsive UI and current website architecture links were checked; Gitee's current release was independently downloaded and matched against the GitHub originals. - [Platform candidate](https://github.com/TNTcraftHIM/Piik/actions/runs/38669095115): all five Apps, both Server architectures and container checks passed at `c534573b`. Subsequent tracked changes only update documentation, the complete-matrix CI budget and race-test coverage. - [Full network comparison](https://github.com/TNTcraftHIM/Piik/actions/runs/38667624364) completed 70 trials before the batch's 45-minute limit. The [remaining scenario](https://github.com/TNTcraftHIM/Piik/actions/runs/38672805155) passed three paired repetitions; all 71 scenario/setting variants are covered, with 58 media and 13 expected/observed unavailable outcomes. Six negative controls passed, and owned resources were cleaned up. These are controlled observations, not a public success rate. - The final validation also includes the shared forwarder under the Go race detector. The separate sole-active-output publication experiment still shows inconsistent recovery: two of four current-code repeats did not pass its recovery observation, so the limitation below remains open. The native SFU allocator still has a measured recovery limitation when only its lowest rate-controlled encoding is active. Fixing that requires a supported upstream demand input; no second controller or allocator fork is introduced. Unmatched capture-failure reports and physical-platform coverage retain their documented evidence limits. ## Release notes ### 中文 这是一次连接与播放稳定性更新,重点改善重连、弱网后的画质恢复和下载镜像可靠性。与 Piik 2.0.0 保持兼容。 - 修复连接等待超时后过早跳过备用线路的问题,保留尚未尝试的媒体服务器兜底机会。 - 改善原生分享在网络拥塞后的画质恢复,并修复转发和媒体服务器发布链路上的视频重传协商遗漏。 - 修复原生观看准备超时后的清理与重试,以及音量从零恢复时的异常。 - 避免可选的 IPv6 端口映射拖慢 IPv4 准备,并修正多网卡环境下的 NAT 预测观测归属。 - 修复昵称编辑、聊天字数变化引起的布局移动;保持 App 提示简洁,并为更新提示补充官网备用下载入口。 - 修复 Gitee 镜像同步在传输中途断开时未重试的问题,校验通过后才完成镜像发布。 仍在跟进:部分原生媒体服务器链路的弱网后恢复仍可能偏慢;尚缺匹配诊断的采集失败反馈不能确认已解决。 ### English This maintenance update improves connection and playback recovery after interruptions and congestion, along with download-mirror reliability. It remains compatible with Piik 2.0.0. - Preserve untried media-server fallback routes when a connection reaches its waiting deadline. - Improve native sharing quality recovery after congestion and fix missing video retransmission negotiation in forwarding and media-server publication paths. - Correct cleanup and retry after native viewing preparation expires, and restore playback volume correctly from zero. - Prevent optional IPv6 port mapping from delaying IPv4 preparation, and associate NAT-prediction observations with the correct local interface. - Stabilize nickname editing and chat counters, keep App guidance unobtrusive, and add the website's alternate downloads to update notices. - Retry interrupted Gitee mirror transfers and complete publication only after verification succeeds. Still under investigation: recovery after congestion can remain slow on some native media-server paths. Capture-failure reports without matching diagnostics are not claimed as resolved.
708 lines
31 KiB
TypeScript
708 lines
31 KiB
TypeScript
import { afterEach, expect, it, vi } from "vitest";
|
|
import type { SignalPayload } from "../src/shared/protocol";
|
|
import type { NativeClient } from "../src/client/native/client";
|
|
import { NativeMediaBridge } from "../src/client/native/media-bridge";
|
|
import { VIEWER_AUTOMATIC_RECOVERY_TIMEOUT_MS, ViewerPeer } from "../src/client/webrtc/viewer-peer";
|
|
import { EMPTY_METRICS, type PeerSnapshot } from "../src/client/types";
|
|
import type { NativeClientEvent } from "../src/client/native/wire";
|
|
import {
|
|
NativeCapableViewerPeer,
|
|
offerHasNativeVideoCodec,
|
|
} from "../src/client/native/native-viewer-peer";
|
|
|
|
afterEach(() => {
|
|
vi.useRealTimers();
|
|
vi.restoreAllMocks();
|
|
vi.unstubAllGlobals();
|
|
});
|
|
|
|
it.each(["commit", "expired", "rpc-expired"])("scopes optional connection preparation to its route: %s", async outcome => {
|
|
vi.useFakeTimers();
|
|
vi.stubGlobal("window", globalThis);
|
|
vi.stubGlobal("MediaStream", class { getTracks() { return []; } });
|
|
vi.stubGlobal("RTCPeerConnection", class { close() {} });
|
|
vi.spyOn(NativeMediaBridge.prototype, "start").mockResolvedValue({} as MediaStream);
|
|
const client = {
|
|
preparePunch: vi.fn(async () => ({ address: "198.51.100.1", port: 40000, step: 1 })),
|
|
runPunch: vi.fn(async () => true), closePunch: vi.fn(async () => undefined),
|
|
receiveOffer: vi.fn(async () => ({ answer: { type: "answer", sdp: "answer" }, audio: false, codec: "vp8" })),
|
|
onEvent: () => () => {}, onClose: () => () => {},
|
|
closeReceiver: vi.fn(async () => {}), closeEdge: vi.fn(async () => {}),
|
|
} as unknown as NativeClient;
|
|
const unavailable = vi.fn(), exhausted = vi.fn(() => true), sent = vi.fn(() => true);
|
|
const peer = new NativeCapableViewerPeer({
|
|
iceServers: [{ urls: ["stun:site.example:3478"] }],
|
|
natPredictionStunUrls: ["stun:site.example:3479", "stun:site.example:3480"],
|
|
}, { sendSignal: sent, sendRestartRequest: () => true, onStream: () => {}, onUpdate: () => {}, onRecoveryExhausted: exhausted },
|
|
{ natPredictionEnabled: true, recoveryOwner: "route" }, async () => client, unavailable, "session", 2);
|
|
// The page accepts a failure only while this peer owns that connection.
|
|
exhausted.mockImplementation(() => peer.hasConnectionId("current"));
|
|
const prepare: SignalPayload = { kind: "punch", connectionId: "current", punch: { phase: "prepare", secret: "42".repeat(32) } };
|
|
try {
|
|
await peer.acceptSignal("parent", prepare);
|
|
await vi.advanceTimersByTimeAsync(0);
|
|
await peer.acceptSignal("parent", { kind: "punch", connectionId: "current", punch: {
|
|
phase: "start", prediction: { address: "198.51.100.2", port: 50000, step: 1 },
|
|
} });
|
|
await vi.advanceTimersByTimeAsync(0);
|
|
if (outcome === "expired") await vi.advanceTimersByTimeAsync(3_500);
|
|
if (outcome === "rpc-expired") vi.mocked(client.receiveOffer).mockRejectedValueOnce(new Error("prepared socket expired"));
|
|
await peer.acceptSignal("parent", {
|
|
kind: "description", connectionId: "current", punched: true,
|
|
description: { type: "offer", sdp: "v=0\r\nm=video 9 UDP/TLS/RTP/SAVPF 96\r\na=sendonly\r\na=rtpmap:96 VP8/90000\r\n" },
|
|
});
|
|
expect(unavailable).not.toHaveBeenCalled();
|
|
if (outcome === "commit") {
|
|
expect(exhausted).not.toHaveBeenCalled();
|
|
expect(client.receiveOffer).toHaveBeenCalledWith("session", "current", expect.anything(), expect.anything(), 2, true);
|
|
await peer.acceptSignal("parent", prepare);
|
|
expect(client.preparePunch).toHaveBeenCalledOnce();
|
|
} else {
|
|
expect(exhausted).toHaveBeenCalledExactlyOnceWith("parent", "current");
|
|
expect(exhausted.mock.results[0].value).toBe(true);
|
|
if (outcome === "expired") expect(client.receiveOffer).not.toHaveBeenCalled();
|
|
}
|
|
} finally { peer.dispose(); }
|
|
});
|
|
|
|
it("uses the offer's STUN destinations for prediction while the next ICE config changes", async () => {
|
|
vi.useFakeTimers();
|
|
vi.stubGlobal("window", globalThis);
|
|
vi.stubGlobal("MediaStream", class { getTracks() { return []; } });
|
|
vi.stubGlobal("RTCPeerConnection", class { close() {} });
|
|
vi.spyOn(NativeMediaBridge.prototype, "start").mockResolvedValue({} as MediaStream);
|
|
let onEvent!: (event: NativeClientEvent) => void;
|
|
const client = {
|
|
receiveOffer: vi.fn(async () => ({ answer: { type: "answer", sdp: "v=0\r\n" }, audio: false, codec: "vp8" })),
|
|
onEvent: (handler: typeof onEvent) => { onEvent = handler; return () => {}; },
|
|
onClose: () => () => {},
|
|
closeReceiver: vi.fn(async () => {}), closeEdge: vi.fn(async () => {}),
|
|
} as unknown as NativeClient;
|
|
const original = {
|
|
iceServers: [{ urls: ["stun:site.example:3478", "stun:other.example:3478"] }],
|
|
natPredictionStunUrls: ["stun:site.example:3479", "stun:site.example:3480"],
|
|
};
|
|
const sent: SignalPayload[] = [];
|
|
const peer = new NativeCapableViewerPeer(original, {
|
|
sendSignal: (_parent, payload) => { sent.push(payload); return true; },
|
|
sendRestartRequest: () => true, onStream: () => {}, onUpdate: () => {},
|
|
}, { natPredictionEnabled: true }, async () => client, () => {}, "session", 2);
|
|
const emit = (index: number, port: number) => onEvent({
|
|
version: 10, type: "edge-candidate", shareId: "session", connectionId: "current",
|
|
candidate: { candidate: `candidate:ns${index} 1 udp 1 203.0.113.7 ${port} typ srflx` },
|
|
});
|
|
const candidates = () => sent.flatMap(payload => payload.kind === "candidate" ? [payload.candidate] : []);
|
|
try {
|
|
await peer.acceptSignal("parent", {
|
|
kind: "description", connectionId: "current",
|
|
description: { type: "offer", sdp: "v=0\r\nm=video 9 UDP/TLS/RTP/SAVPF 96\r\na=sendonly\r\na=rtpmap:96 VP8/90000\r\n" },
|
|
});
|
|
peer.updateIceConfig({
|
|
...original, iceServers: [{ urls: ["stun:other.example:3478", "stun:site.example:3478"] }],
|
|
});
|
|
emit(3, 40006);
|
|
emit(2, 40003); // Ordinary extra destination must not complete a predicted sequence.
|
|
emit(1, 40000);
|
|
expect(candidates()).toHaveLength(3);
|
|
emit(4, 40012);
|
|
expect(candidates()).toHaveLength(12); // Four ordinary candidates plus the bounded eight predictions.
|
|
} finally {
|
|
peer.dispose();
|
|
}
|
|
});
|
|
|
|
it("retires queued candidates when disposed during their delivery", async () => {
|
|
vi.stubGlobal("window", globalThis);
|
|
vi.stubGlobal("MediaStream", class { getTracks() { return []; } });
|
|
let finishCandidate!: () => void;
|
|
const accept = vi.spyOn(ViewerPeer.prototype, "acceptSignal").mockImplementation(
|
|
async (_parent, payload) => {
|
|
if (payload.kind === "candidate") {
|
|
await new Promise<void>(resolve => { finishCandidate = resolve; });
|
|
}
|
|
},
|
|
);
|
|
const peer = new NativeCapableViewerPeer(
|
|
{ iceServers: [] },
|
|
{
|
|
sendSignal: () => true, sendRestartRequest: () => true,
|
|
onStream: () => undefined, onUpdate: () => undefined,
|
|
},
|
|
{}, async () => null, () => undefined, "session", 2,
|
|
);
|
|
try {
|
|
for (const port of [5000, 5001]) {
|
|
await peer.acceptSignal("parent", {
|
|
kind: "candidate", connectionId: "current",
|
|
candidate: { candidate: `candidate:1 1 UDP 2122260223 192.0.2.1 ${port} typ host` },
|
|
});
|
|
}
|
|
const accepting = peer.acceptSignal("parent", {
|
|
kind: "description", connectionId: "current",
|
|
description: { type: "offer", sdp: "v=0\r\n" },
|
|
});
|
|
await vi.waitFor(() => expect(accept).toHaveBeenCalledTimes(2));
|
|
peer.dispose();
|
|
finishCandidate();
|
|
await expect(accepting).resolves.toBeUndefined();
|
|
expect(accept).toHaveBeenCalledTimes(2);
|
|
} finally {
|
|
peer.dispose();
|
|
}
|
|
});
|
|
|
|
it.each(["viewer", "route"] as const)("retires a connected Native receiver on control loss (%s)", async (recoveryOwner) => {
|
|
vi.useFakeTimers();
|
|
vi.stubGlobal("window", globalThis);
|
|
vi.stubGlobal("MediaStream", class { getTracks() { return []; } });
|
|
vi.stubGlobal("RTCPeerConnection", class { close() {} });
|
|
vi.spyOn(NativeMediaBridge.prototype, "start").mockResolvedValue({} as MediaStream);
|
|
vi.spyOn(NativeMediaBridge.prototype, "collectMetrics").mockResolvedValue({ ...EMPTY_METRICS });
|
|
vi.spyOn(NativeMediaBridge.prototype, "decodedVideoFrames").mockResolvedValue(null);
|
|
let onEvent!: (event: NativeClientEvent) => void;
|
|
let onClose!: () => void;
|
|
const client = {
|
|
receiveOffer: async () => ({
|
|
answer: { type: "answer", sdp: "v=0\r\n" }, audio: false, codec: "vp8",
|
|
}),
|
|
onEvent: (handler: typeof onEvent) => { onEvent = handler; return () => undefined; },
|
|
onClose: (handler: typeof onClose) => { onClose = handler; return () => undefined; },
|
|
closeReceiver: vi.fn(async () => undefined),
|
|
closeEdge: vi.fn(async () => undefined),
|
|
} as unknown as NativeClient;
|
|
const unavailable = vi.fn();
|
|
const restart = vi.fn(() => true);
|
|
const exhausted = vi.fn(() => true);
|
|
const updates: PeerSnapshot[] = [];
|
|
const peer = new NativeCapableViewerPeer(
|
|
{ iceServers: [] },
|
|
{
|
|
sendSignal: () => true, sendRestartRequest: restart,
|
|
onStream: () => undefined, onUpdate: (value) => updates.push(value),
|
|
onRecoveryExhausted: exhausted,
|
|
},
|
|
{ recoveryOwner }, async () => client, unavailable, "session", 2,
|
|
);
|
|
try {
|
|
await peer.acceptSignal("parent", {
|
|
kind: "description", connectionId: "current",
|
|
description: { type: "offer", sdp: "v=0\r\nm=video 9 UDP/TLS/RTP/SAVPF 96\r\na=sendonly\r\na=rtpmap:96 VP8/90000\r\n" },
|
|
});
|
|
const connected = {
|
|
version: 10, shareId: "session", connectionId: "current", type: "edge-state", state: "connected",
|
|
} as const;
|
|
onEvent(connected);
|
|
expect(peer.isConnected()).toBe(true);
|
|
expect(peer.nativeSource).not.toBeNull();
|
|
|
|
onClose();
|
|
expect(peer.isConnected()).toBe(false);
|
|
expect(peer.nativeSource).toBeNull();
|
|
expect(updates.at(-1)?.connectionState).toBe("failed");
|
|
// A queued event cannot revive the receiver that owns the dead bridge.
|
|
onEvent(connected);
|
|
onClose();
|
|
expect(peer.isConnected()).toBe(false);
|
|
expect(unavailable).toHaveBeenCalledOnce();
|
|
if (recoveryOwner === "viewer") {
|
|
expect(restart).toHaveBeenCalledExactlyOnceWith("parent", "current", true);
|
|
expect(exhausted).not.toHaveBeenCalled();
|
|
await vi.advanceTimersByTimeAsync(VIEWER_AUTOMATIC_RECOVERY_TIMEOUT_MS);
|
|
} else {
|
|
expect(restart).not.toHaveBeenCalled();
|
|
}
|
|
expect(exhausted).toHaveBeenCalledExactlyOnceWith("parent", "current");
|
|
} finally {
|
|
peer.dispose();
|
|
}
|
|
});
|
|
|
|
it.each([false, true])("ignores a late Native offer after control loss (disposed=%s)", async (disposeOnFailure) => {
|
|
vi.useFakeTimers();
|
|
vi.stubGlobal("window", globalThis);
|
|
vi.stubGlobal("MediaStream", class { getTracks() { return []; } });
|
|
vi.stubGlobal("RTCPeerConnection", class { close() {} });
|
|
const bridgeStart = vi.spyOn(NativeMediaBridge.prototype, "start").mockResolvedValue({} as MediaStream);
|
|
let resolveOffer!: (value: Awaited<ReturnType<NativeClient["receiveOffer"]>>) => void;
|
|
const receiveOffer = vi.fn(() => new Promise<Awaited<ReturnType<NativeClient["receiveOffer"]>>>((resolve) => {
|
|
resolveOffer = resolve;
|
|
}));
|
|
let onClose!: () => void;
|
|
const closeReceiver = vi.fn(async () => undefined);
|
|
const client = {
|
|
receiveOffer,
|
|
onEvent: () => () => undefined,
|
|
onClose: (handler: typeof onClose) => { onClose = handler; return () => undefined; },
|
|
closeReceiver, closeEdge: vi.fn(async () => undefined),
|
|
} as unknown as NativeClient;
|
|
const sendSignal = vi.fn(() => true);
|
|
const onStream = vi.fn();
|
|
const restart = vi.fn(() => true);
|
|
const unavailable = vi.fn();
|
|
const updates: PeerSnapshot[] = [];
|
|
let peer!: NativeCapableViewerPeer;
|
|
peer = new NativeCapableViewerPeer(
|
|
{ iceServers: [] },
|
|
{
|
|
sendSignal, sendRestartRequest: restart, onStream,
|
|
onUpdate: (value) => {
|
|
updates.push(value);
|
|
if (disposeOnFailure && value.connectionState === "failed") peer.dispose();
|
|
},
|
|
},
|
|
{}, async () => client, unavailable, "session", 2,
|
|
);
|
|
try {
|
|
const accepting = peer.acceptSignal("parent", {
|
|
kind: "description", connectionId: "current",
|
|
description: { type: "offer", sdp: "v=0\r\nm=video 9 UDP/TLS/RTP/SAVPF 96\r\na=sendonly\r\na=rtpmap:96 VP8/90000\r\n" },
|
|
});
|
|
await vi.waitFor(() => expect(receiveOffer).toHaveBeenCalledOnce());
|
|
onClose();
|
|
resolveOffer({ answer: { type: "answer", sdp: "v=0\r\n" }, audio: false, codec: "vp8", reused: false });
|
|
await accepting;
|
|
|
|
expect(updates.at(-1)?.connectionState).toBe("failed");
|
|
expect(peer.isConnected()).toBe(false);
|
|
expect(peer.nativeSource).toBeNull();
|
|
expect(closeReceiver).toHaveBeenCalledWith("session", "current");
|
|
expect(sendSignal).not.toHaveBeenCalled();
|
|
expect(onStream).not.toHaveBeenCalled();
|
|
expect(bridgeStart).not.toHaveBeenCalled();
|
|
expect(unavailable).toHaveBeenCalledOnce();
|
|
expect(restart).toHaveBeenCalledTimes(disposeOnFailure ? 0 : 1);
|
|
} finally {
|
|
peer.dispose();
|
|
}
|
|
});
|
|
|
|
it.each(["reused", "replaced", "answer-lost", "control-lost"])("keeps Native receiver lifetimes coherent through renegotiation (%s)", async (outcome) => {
|
|
vi.useFakeTimers();
|
|
vi.stubGlobal("window", globalThis);
|
|
vi.stubGlobal("MediaStream", class { getTracks() { return []; } });
|
|
vi.stubGlobal("RTCPeerConnection", class { close() {} });
|
|
const bridges: NativeMediaBridge[] = [];
|
|
const bridgeStart = vi.spyOn(NativeMediaBridge.prototype, "start").mockImplementation(async function (this: NativeMediaBridge) {
|
|
bridges.push(this);
|
|
return {} as MediaStream;
|
|
});
|
|
let closeControl!: () => void;
|
|
let event!: (event: NativeClientEvent) => void;
|
|
const receiveOffer = vi.fn(async () => ({
|
|
answer: { type: "answer" as const, sdp: "answer-sdp" }, audio: false, codec: "vp8" as const, reused: false,
|
|
}));
|
|
const closeReceiver = vi.fn(async () => undefined);
|
|
const closeEdge = vi.fn(async () => undefined);
|
|
const client = {
|
|
health: { nativeMedia: { receiverReuse: true } }, receiveOffer, closeReceiver, closeEdge,
|
|
onEvent: (listener: typeof event) => { event = listener; return () => {}; },
|
|
onClose: (listener: typeof closeControl) => { closeControl = listener; return () => {}; },
|
|
} as unknown as NativeClient;
|
|
const sendSignal = vi.fn(() => true);
|
|
const onStream = vi.fn();
|
|
const unavailable = vi.fn();
|
|
const peer = new NativeCapableViewerPeer({ iceServers: [] }, {
|
|
sendSignal, sendRestartRequest: () => true, onStream, onUpdate: () => {},
|
|
}, {}, async () => client, unavailable, "session", 2);
|
|
const offer = (ice: string): SignalPayload => ({
|
|
kind: "description", connectionId: "current", description: { type: "offer",
|
|
sdp: `v=0\r\na=ice-ufrag:${ice}\r\nm=video 9 UDP/TLS/RTP/SAVPF 96\r\na=sendonly\r\na=rtpmap:96 VP8/90000\r\n` },
|
|
});
|
|
try {
|
|
await peer.acceptSignal("parent", offer("first"));
|
|
event({ version: 10, type: "edge-state", shareId: "session", connectionId: "current", state: "connected" });
|
|
const source = peer.nativeSource;
|
|
receiveOffer.mockImplementationOnce(async () => {
|
|
if (outcome === "replaced") {
|
|
// Replacement closes the old local edge before its answer reaches JS.
|
|
(bridges[0] as unknown as { onFailed(): void }).onFailed();
|
|
}
|
|
if (outcome === "control-lost") closeControl();
|
|
return { answer: { type: "answer", sdp: "new-answer-sdp" }, audio: false, codec: "vp8", reused: outcome !== "replaced" };
|
|
});
|
|
if (outcome === "answer-lost") sendSignal.mockReturnValue(false);
|
|
await peer.acceptSignal("parent", offer("restarted"));
|
|
expect(receiveOffer).toHaveBeenCalledTimes(2);
|
|
if (outcome === "control-lost") {
|
|
expect(peer.nativeSource).toBeNull();
|
|
expect(unavailable).toHaveBeenCalledOnce();
|
|
} else {
|
|
expect(closeReceiver).not.toHaveBeenCalled();
|
|
expect(unavailable).not.toHaveBeenCalled();
|
|
expect(bridgeStart).toHaveBeenCalledTimes(outcome === "replaced" ? 2 : 1);
|
|
expect(onStream).toHaveBeenCalledTimes(outcome === "replaced" ? 2 : 1);
|
|
expect(peer.nativeSource?.generation).toBe(source!.generation + (outcome === "replaced" ? 1 : 0));
|
|
if (outcome !== "replaced") {
|
|
expect(closeEdge).not.toHaveBeenCalled();
|
|
expect(peer.isConnected()).toBe(true);
|
|
}
|
|
}
|
|
} finally { peer.dispose(); }
|
|
});
|
|
|
|
it("admits one active sending H264 or VP8 video section, not unrelated SDP codec text", () => {
|
|
const video = (codec: string, direction = "sendonly", port = 9, payload = 96) => [
|
|
`m=video ${port} UDP/TLS/RTP/SAVPF ${payload}`,
|
|
`a=${direction}`,
|
|
`a=rtpmap:96 ${codec}/90000`,
|
|
"a=fmtp:96 profile-level-id=42e01f;packetization-mode=1",
|
|
"",
|
|
].join("\r\n");
|
|
expect(offerHasNativeVideoCodec(video("H264"))).toBe(true);
|
|
expect(offerHasNativeVideoCodec(video("VP8"))).toBe(true);
|
|
expect(offerHasNativeVideoCodec(video("VP8", "sendrecv"))).toBe(true);
|
|
expect(offerHasNativeVideoCodec("a=group:BUNDLE 0\r\n" +
|
|
video("VP8", "sendonly", 0) + "a=bundle-only\r\na=mid:0\r\n")).toBe(true);
|
|
expect(offerHasNativeVideoCodec("m=video 9 UDP/TLS/RTP/SAVPF 96 97\r\n" +
|
|
"a=sendonly\r\na=rtpmap:96 H264/90000\r\na=rtpmap:97 VP8/90000\r\n")).toBe(true);
|
|
for (const offer of [
|
|
video("VP8", "recvonly"), video("VP8", "inactive"),
|
|
video("VP8", "sendonly", 0), video("VP8", "sendonly", 9, 97),
|
|
video("VP8", "sendonly", 0) + "a=bundle-only\r\na=mid:0\r\n",
|
|
video("VP9"), video("H264") + video("VP8"),
|
|
"m=audio 9 UDP/TLS/RTP/SAVPF 96\r\na=rtpmap:96 VP8/90000\r\n",
|
|
]) expect(offerHasNativeVideoCodec(offer)).toBe(false);
|
|
});
|
|
|
|
it.each([
|
|
["42e01f", "1", true], ["42c01f", "1", true],
|
|
["4de01f", "1", true], ["58c01f", "1", true],
|
|
["42e00b", "1", true], ["42e033", "1", true], ["42e034", "1", true],
|
|
["42e03c", "1", false],
|
|
["4d001f", "1", false], ["64001f", "1", false], ["42001f", "1", false],
|
|
["42e11f", "1", false], ["42e035", "1", false], ["42e03c", "1", false],
|
|
["42e01f=invalid", "1", false],
|
|
["", "1", false], ["42e01f", "0", false], ["42e01f", "", false],
|
|
])("matches Native H264 forwarding admission: profile=%s, packetization=%s", (profile, mode, supported) => {
|
|
const offer = "m=video 9 UDP/TLS/RTP/SAVPF 96\r\na=sendonly\r\n" +
|
|
"a=rtpmap:96 H264/90000\r\n" +
|
|
`a=fmtp:96 profile-level-id=${profile};packetization-mode=${mode}\r\n`;
|
|
expect(offerHasNativeVideoCodec(offer)).toBe(supported);
|
|
});
|
|
|
|
it("sends an unsupported Native format straight to the Browser without failing the App", async () => {
|
|
vi.stubGlobal("MediaStream", class { getTracks() { return []; } });
|
|
const browserSignal = vi.spyOn(ViewerPeer.prototype, "acceptSignal").mockResolvedValue();
|
|
const acquire = vi.fn(async () => null);
|
|
const unavailable = vi.fn();
|
|
const restart = vi.fn(() => true);
|
|
const peer = new NativeCapableViewerPeer({ iceServers: [] }, {
|
|
sendSignal: () => true, sendRestartRequest: restart,
|
|
onStream: () => undefined, onUpdate: () => undefined,
|
|
}, {}, acquire, unavailable, "session", 2);
|
|
const offer: SignalPayload = { kind: "description", connectionId: "current", description: {
|
|
type: "offer", sdp: "m=video 9 UDP/TLS/RTP/SAVPF 96\r\na=sendonly\r\n" +
|
|
"a=rtpmap:96 H264/90000\r\na=fmtp:96 profile-level-id=64001f;packetization-mode=1\r\n",
|
|
}};
|
|
try {
|
|
await peer.acceptSignal("parent", offer);
|
|
expect(browserSignal).toHaveBeenCalledExactlyOnceWith("parent", offer);
|
|
expect(acquire).not.toHaveBeenCalled();
|
|
expect(unavailable).not.toHaveBeenCalled();
|
|
expect(restart).not.toHaveBeenCalled();
|
|
} finally { peer.dispose(); }
|
|
});
|
|
|
|
it("does not create a browser backend after deferred native discovery is disposed", async () => {
|
|
let resolveClient: (value: null) => void = () => undefined;
|
|
const nativeClient = new Promise<null>((resolve) => {
|
|
resolveClient = resolve;
|
|
});
|
|
const peer = new NativeCapableViewerPeer(
|
|
{ iceServers: [] },
|
|
{
|
|
sendSignal: () => true,
|
|
sendRestartRequest: () => true,
|
|
onStream: () => undefined,
|
|
onUpdate: () => undefined,
|
|
},
|
|
{},
|
|
() => nativeClient,
|
|
() => undefined,
|
|
"session",
|
|
2,
|
|
);
|
|
const accepted = peer.acceptSignal("parent", {
|
|
kind: "description",
|
|
connectionId: "connection",
|
|
description: {
|
|
type: "offer",
|
|
sdp: [
|
|
"v=0",
|
|
"m=video 9 UDP/TLS/RTP/SAVPF 96",
|
|
"a=sendonly",
|
|
"a=rtpmap:96 H264/90000",
|
|
"",
|
|
].join("\r\n"),
|
|
},
|
|
});
|
|
peer.dispose();
|
|
resolveClient(null);
|
|
await accepted;
|
|
expect(peer.getConnectionIdentity()).toBeNull();
|
|
});
|
|
|
|
it.each(["route", "viewer"] as const)("recovers an answer signaling failure without disabling native (%s)", async (recoveryOwner) => {
|
|
vi.stubGlobal("window", globalThis);
|
|
vi.stubGlobal("MediaStream", class { getTracks() { return []; } });
|
|
vi.stubGlobal("RTCPeerConnection", class { close() {} });
|
|
const receiveOffer = vi.fn(async () => ({
|
|
answer: { type: "answer", sdp: "v=0\r\n" }, audio: false, codec: "vp8",
|
|
}));
|
|
const closeReceiver = vi.fn(async () => undefined);
|
|
const client = {
|
|
receiveOffer,
|
|
onEvent: () => () => undefined,
|
|
onClose: () => () => undefined,
|
|
closeReceiver,
|
|
closeEdge: vi.fn(async () => undefined),
|
|
} as unknown as NativeClient;
|
|
let available = true;
|
|
const acquire = vi.fn(async () => available ? client : null);
|
|
const unavailable = vi.fn(() => { available = false; });
|
|
const restart = vi.fn(() => true);
|
|
const exhausted = vi.fn(() => true);
|
|
let signalOnline = false;
|
|
const peer = new NativeCapableViewerPeer(
|
|
{ iceServers: [] },
|
|
{
|
|
sendSignal: () => signalOnline,
|
|
sendRestartRequest: restart,
|
|
onStream: () => undefined,
|
|
onUpdate: () => undefined,
|
|
onRecoveryExhausted: exhausted,
|
|
},
|
|
{ recoveryOwner },
|
|
acquire,
|
|
unavailable,
|
|
"session",
|
|
2,
|
|
);
|
|
const offer = (connectionId: string): SignalPayload => ({
|
|
kind: "description", connectionId,
|
|
description: { type: "offer", sdp: "v=0\r\nm=video 9 UDP/TLS/RTP/SAVPF 96\r\na=sendonly\r\na=rtpmap:96 VP8/90000\r\n" },
|
|
});
|
|
try {
|
|
// A transient room-signaling outage at the answer must not disable
|
|
// Native reception for the session: close only this receiver and run
|
|
// the ordinary recovery path.
|
|
await peer.acceptSignal("parent", offer("first"));
|
|
expect(unavailable).not.toHaveBeenCalled();
|
|
expect(peer.nativeSource).toBeNull();
|
|
expect(closeReceiver).toHaveBeenCalledWith("session", "first");
|
|
if (recoveryOwner === "viewer") {
|
|
expect(restart).toHaveBeenCalledWith("parent", "first", true);
|
|
expect(exhausted).not.toHaveBeenCalled();
|
|
} else {
|
|
expect(exhausted).toHaveBeenCalledWith("parent", "first");
|
|
expect(restart).not.toHaveBeenCalled();
|
|
}
|
|
|
|
// With signaling back online, the next offer re-acquires the native path.
|
|
signalOnline = true;
|
|
vi.spyOn(NativeMediaBridge.prototype, "start").mockResolvedValue(
|
|
new (class {})() as never,
|
|
);
|
|
await peer.acceptSignal("parent", offer("second"));
|
|
expect(acquire).toHaveBeenCalledTimes(2);
|
|
expect(receiveOffer).toHaveBeenCalledTimes(2);
|
|
expect(unavailable).not.toHaveBeenCalled();
|
|
} finally {
|
|
peer.dispose();
|
|
}
|
|
});
|
|
|
|
it("still disables native on a genuine failure after a signaling failure", async () => {
|
|
vi.stubGlobal("window", globalThis);
|
|
vi.stubGlobal("MediaStream", class { getTracks() { return []; } });
|
|
vi.stubGlobal("RTCPeerConnection", class { close() {} });
|
|
let eventHandler: ((event: unknown) => void) | null = null;
|
|
const receiveOffer = vi.fn(async () => ({
|
|
answer: { type: "answer", sdp: "v=0\r\n" }, audio: false, codec: "vp8",
|
|
}));
|
|
const client = {
|
|
receiveOffer,
|
|
onEvent: (handler: (event: unknown) => void) => {
|
|
eventHandler = handler;
|
|
return () => undefined;
|
|
},
|
|
onClose: () => () => undefined,
|
|
closeReceiver: vi.fn(async () => undefined),
|
|
closeEdge: vi.fn(async () => undefined),
|
|
} as unknown as NativeClient;
|
|
const unavailable = vi.fn();
|
|
const peer = new NativeCapableViewerPeer(
|
|
{ iceServers: [] },
|
|
{
|
|
sendSignal: () => false,
|
|
sendRestartRequest: () => true,
|
|
onStream: () => undefined,
|
|
onUpdate: () => undefined,
|
|
onRecoveryExhausted: () => true,
|
|
},
|
|
{},
|
|
async () => client,
|
|
unavailable,
|
|
"session",
|
|
2,
|
|
);
|
|
try {
|
|
await peer.acceptSignal("parent", {
|
|
kind: "description",
|
|
connectionId: "first",
|
|
description: { type: "offer", sdp: "v=0\r\nm=video 9 UDP/TLS/RTP/SAVPF 96\r\na=sendonly\r\na=rtpmap:96 VP8/90000\r\n" },
|
|
});
|
|
expect(unavailable).not.toHaveBeenCalled();
|
|
|
|
// A genuine native failure on the same connection must still disable
|
|
// Native for the session: the signaling path must not have latched the
|
|
// failure state.
|
|
eventHandler!({ shareId: "session", type: "share-ended", failed: true });
|
|
expect(unavailable).toHaveBeenCalledOnce();
|
|
} finally {
|
|
peer.dispose();
|
|
}
|
|
});
|
|
|
|
it.each([
|
|
["route", "initialize"], ["route", "start"],
|
|
["viewer", "initialize"], ["viewer", "start"],
|
|
] as const)("keeps %s bridge %s failure unavailable across replacement peers", async (recoveryOwner, failureStage) => {
|
|
vi.stubGlobal("window", globalThis);
|
|
vi.stubGlobal("MediaStream", class { getTracks() { return []; } });
|
|
vi.stubGlobal("RTCPeerConnection", class {
|
|
constructor() { if (failureStage === "initialize") throw new DOMException("Peer unavailable", "NotSupportedError"); }
|
|
close() {}
|
|
});
|
|
const browserSignal = vi.spyOn(ViewerPeer.prototype, "acceptSignal").mockResolvedValue();
|
|
const bridgeStart = vi.spyOn(NativeMediaBridge.prototype, "start").mockRejectedValue(new Error("bridge failed"));
|
|
const receiveOffer = vi.fn(async () => ({
|
|
answer: { type: "answer", sdp: "v=0\r\n" }, audio: false, codec: "vp8",
|
|
}));
|
|
const client = {
|
|
receiveOffer,
|
|
onEvent: () => () => undefined,
|
|
onClose: () => () => undefined,
|
|
closeReceiver: vi.fn(async () => undefined),
|
|
closeEdge: vi.fn(async () => undefined),
|
|
} as unknown as NativeClient;
|
|
let available = true;
|
|
const acquire = vi.fn(async () => available ? client : null);
|
|
const unavailable = vi.fn(() => { available = false; });
|
|
const recover = vi.fn(() => {
|
|
expect(available).toBe(false);
|
|
return true;
|
|
});
|
|
const create = () => new NativeCapableViewerPeer(
|
|
{ iceServers: [] },
|
|
{
|
|
sendSignal: () => true,
|
|
sendRestartRequest: recover,
|
|
onStream: () => undefined,
|
|
onUpdate: () => undefined,
|
|
onRecoveryExhausted: recover,
|
|
},
|
|
{ recoveryOwner },
|
|
acquire,
|
|
unavailable,
|
|
"session",
|
|
2,
|
|
);
|
|
const offer = (connectionId: string): SignalPayload => ({
|
|
kind: "description", connectionId,
|
|
description: { type: "offer", sdp: "v=0\r\nm=video 9 UDP/TLS/RTP/SAVPF 96\r\na=sendonly\r\na=rtpmap:96 VP8/90000\r\n" },
|
|
});
|
|
const first = create();
|
|
const queued = create();
|
|
try {
|
|
await first.acceptSignal("parent", offer("first"));
|
|
await vi.waitFor(() => expect(unavailable).toHaveBeenCalledOnce());
|
|
expect(recover).toHaveBeenCalledOnce();
|
|
first.dispose();
|
|
await queued.acceptSignal("parent", offer("queued"));
|
|
expect(browserSignal).toHaveBeenCalledOnce();
|
|
const replacement = create();
|
|
try {
|
|
await replacement.acceptSignal("parent", offer("replacement"));
|
|
expect(browserSignal).toHaveBeenCalledTimes(2);
|
|
expect(receiveOffer).toHaveBeenCalledOnce();
|
|
expect(bridgeStart).toHaveBeenCalledTimes(failureStage === "initialize" ? 0 : 1);
|
|
expect(acquire).toHaveBeenCalledTimes(3);
|
|
} finally {
|
|
replacement.dispose();
|
|
}
|
|
} finally {
|
|
first.dispose();
|
|
queued.dispose();
|
|
}
|
|
});
|
|
|
|
it.each(["first", "replacement", "failed-offer"])("keeps committed route recovery and its budget across backend replacement (%s)", async (scenario) => {
|
|
vi.useFakeTimers();
|
|
vi.stubGlobal("window", globalThis);
|
|
vi.stubGlobal("MediaStream", class { getTracks() { return []; } });
|
|
vi.stubGlobal("RTCPeerConnection", class { close() {} });
|
|
vi.spyOn(NativeMediaBridge.prototype, "start").mockResolvedValue({} as MediaStream);
|
|
vi.spyOn(NativeMediaBridge.prototype, "collectMetrics").mockResolvedValue({ ...EMPTY_METRICS });
|
|
vi.spyOn(NativeMediaBridge.prototype, "decodedVideoFrames").mockResolvedValue(null);
|
|
let onEvent!: (event: NativeClientEvent) => void;
|
|
const receiveOffer = vi.fn(async () => ({ answer: { type: "answer", sdp: "v=0\r\n" }, audio: false, codec: "vp8" }));
|
|
const client = {
|
|
receiveOffer,
|
|
onEvent: (fn: typeof onEvent) => { onEvent = fn; return () => undefined; },
|
|
onClose: () => () => undefined,
|
|
closeReceiver: vi.fn(async () => undefined), closeEdge: vi.fn(async () => undefined),
|
|
} as unknown as NativeClient;
|
|
const restart = vi.fn(() => true);
|
|
const exhausted = vi.fn(() => true);
|
|
const options = { recoveryOwner: "route" as const };
|
|
const peer = new NativeCapableViewerPeer({ iceServers: [] }, {
|
|
sendSignal: () => true, sendRestartRequest: restart,
|
|
onStream: () => undefined, onUpdate: () => undefined, onRecoveryExhausted: exhausted,
|
|
}, options, async () => client, () => undefined, "session", 2);
|
|
const offer = (connectionId: string) => ({ kind: "description" as const, connectionId,
|
|
description: { type: "offer" as const, sdp: "v=0\r\nm=video 9 UDP/TLS/RTP/SAVPF 96\r\na=sendonly\r\na=rtpmap:96 VP8/90000\r\n" }});
|
|
const state = (connectionId: string, value: "connected" | "failed") => onEvent({
|
|
version: 10, shareId: "session", connectionId, type: "edge-state", state: value,
|
|
});
|
|
try {
|
|
await peer.acceptSignal("parent", offer("first"));
|
|
state("first", "connected");
|
|
peer.activatePreparedRoute();
|
|
expect(options.recoveryOwner).toBe("route"); // Caller options are not mutable route state.
|
|
const connectionId = scenario === "replacement" ? "replacement" : "first";
|
|
if (scenario === "replacement") {
|
|
await peer.acceptSignal("parent", offer(connectionId));
|
|
state(connectionId, "connected");
|
|
}
|
|
state(connectionId, "failed");
|
|
expect(restart).toHaveBeenCalledExactlyOnceWith("parent", connectionId, false);
|
|
expect(exhausted).not.toHaveBeenCalled();
|
|
await vi.advanceTimersByTimeAsync(VIEWER_AUTOMATIC_RECOVERY_TIMEOUT_MS);
|
|
expect(restart).toHaveBeenNthCalledWith(2, "parent", connectionId, true);
|
|
|
|
// A new physical ID is the requested rebuild, not a recovered parent.
|
|
const retiredEvent = onEvent;
|
|
if (scenario === "failed-offer") receiveOffer.mockRejectedValueOnce(new Error("receiver unavailable"));
|
|
await peer.acceptSignal("parent", offer("rebuilt"));
|
|
retiredEvent({ version: 10, shareId: "session", connectionId, type: "edge-state", state: "connected" });
|
|
state("rebuilt", "failed");
|
|
expect(restart).toHaveBeenCalledTimes(2);
|
|
expect(exhausted).toHaveBeenCalledExactlyOnceWith("parent", "rebuilt");
|
|
|
|
// Explicit retry owns a new bounded request and must report its outcome.
|
|
expect(peer.requestRecovery(true)).toBe(true);
|
|
await vi.advanceTimersByTimeAsync(VIEWER_AUTOMATIC_RECOVERY_TIMEOUT_MS);
|
|
expect(exhausted).toHaveBeenCalledTimes(2);
|
|
|
|
// Only actual recovery or a different parent gives a fresh budget.
|
|
await peer.acceptSignal("parent", offer("healthy"));
|
|
state("healthy", "connected");
|
|
state("healthy", "failed");
|
|
expect(restart).toHaveBeenNthCalledWith(4, "parent", "healthy", false);
|
|
await peer.acceptSignal("other-parent", offer("other-connection"));
|
|
state("other-connection", "failed");
|
|
expect(restart).toHaveBeenNthCalledWith(5, "other-parent", "other-connection", false);
|
|
} finally { peer.dispose(); }
|
|
});
|